How to connect to ElasticSearch via Spring Boot App Startup?


#1

Am using Spring Boot along with ElasticSearch's Java Client
to connect to a local ElasticSearch 5.5.0 instance by using the
following code inside:

public void (String... args)

Here's the current code:

@SpringBootApplication
public class Application implements CommandLineRunner {

	Logger log = Logger.getLogger(Application.class);

	public static void main(String args[]) {
		SpringApplication.run(Application.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		log.info("Inside run() method");
		Settings settings = Settings.builder().put("cluster.name", "app-cluster")
				                              .put("client.transport.sniff", true)
				                              .build();

		TransportClient client = new PreBuiltTransportClient(settings);

		client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

		// Add documents
		IndexResponse response = client.prepareIndex("test", "tests")
			.setSource(
				jsonBuilder().startObject()
				 			 .field("message", "Hello!")
				 			 .field("Date", new Date())
				 			 .endObject()
			).get();
	}

}

My pom.xml:

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>1.5.4.RELEASE</version>
</parent>

<properties>
	<java.version>1.8</java.version>
</properties>

<repositories>
	<repository>
		<id>spring-releases</id>
		<url>https://repo.spring.io/libs-release</url>
	</repository>
</repositories>

<pluginRepositories>
	<pluginRepository>
		<id>spring-releases</id>
		<url>https://repo.spring.io/libs-release</url>
	</pluginRepository>
</pluginRepositories>

<dependencies>
	<!-- Spring -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>

	<!-- Elasticsearch -->
	<dependency>
		<groupId>org.elasticsearch</groupId>
		<artifactId>elasticsearch</artifactId>			
		<version>5.5.0</version>
	</dependency>

	<dependency>
		<groupId>org.elasticsearch.client</groupId>
		<artifactId>transport</artifactId>
		<version>5.5.0</version>
	</dependency>
 </dependencies>

Question:

  1. Is there an Spring based annotation that I can use to autoload config files and start the connection to the ElasticSearch server in my Spring Boot app? Kind of like a ServletInitializer or ServletFilter?

  2. Where (what file in the codebase) would I place this and have my Application load it (connect via settings and client) upon Spring Boot Startup?

  3. Also, is there a way to set it up so an external client can call the client.disconnect()?


(system) #2

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.