springboot集成JestClient连接elasticsearch-5.x

来源:互联网 发布:阿里云主机记录 编辑:程序博客网 时间:2024/06/04 20:09

   需要的依赖

<dependency>   <groupId>io.searchbox</groupId>   <artifactId>jest</artifactId>   <version>5.3.3</version></dependency><dependency>   <groupId>org.elasticsearch</groupId>   <artifactId>elasticsearch</artifactId>   <version>5.5.3</version></dependency>
<!--添加下面的依赖,请在resource下再添加log4j2.xml文件-->
<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文件中的配置信息注入到实例中

@Servicepublic 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

原创粉丝点击