springboot集成JestClient连接elasticsearch-5.x

   需要的依赖

<dependency>
   <groupId>io.searchboxgroupId>
   <artifactId>jestartifactId>
   <version>5.3.3version>
dependency>
<dependency>
   <groupId>org.elasticsearchgroupId>
   <artifactId>elasticsearchartifactId>
   <version>5.5.3version>
dependency>
< dependency >
< groupId >org.apache.logging.log4j groupId >
< artifactId >log4j-core artifactId >
<
version >2.6.2 version >
dependency >

    yml文件中填写配置,当你填写一下信息时会有提示,这都得益于spring-boot-autoconfigure这个jar包,这个jar已经包含在spring-boot-starter-parent依赖里面,一般springboot的启动类上都有@SpringBootApplication,查看这个注解里面又包含@EnableAutoConfiguration


spring:
  elasticsearch:
    jest:
      uris: http://192.168.110.31:9092,http://192.168.110.31:9093,http://192.168.110.31:9094
      username: elastic
      password: changeme
      read-timeout: 20000 #读取超时    
      connection-timeout: 20000 #连接超时
    除了上面配置的属性以外,还可以配置代理,根据自己的需要选择

spring:
  elasticsearch:
    jest:
      proxy:
        host:
        port:


        然后在你要使用的类里直接注入JestClient就可以开发了,因为应用启动后,系统会自动将yml文件中的配置信息注入到实例中

@Service
public class StudentService {
    private Logger logger = LoggerFactory.getLogger(StudentService.class);
    
    @Autowired
    JestClient jestClient;

    public void search(){
       //先定义一个action(增删改查),例如search       
       Search search = new Search.Builder(query).addIndex(index).build();
       //执行action,返回结果              
       SearchResult result = jestClient.execute(search);
       //处理结果集
       ...........省略
    }

       是不是感觉和spring-data-elasticsearch集成方式有点相似呢,只不过spring-data-elasticsearch基于tcp协议连接方式,而JestClient基于http协议

    注意:此处JestClient是单例的,在多线程并发访问时注意加锁同步或者使用异步执行jestClient.executeAsync()或者自定义JestClientFactory设置HttpClientConfig的多线程属性为true,从而重新构造JestClient。

    参考地址http://www.jb51.net/article/127390.htm

你可能感兴趣的:(ElasticSearch)