Spring boot集成Elasticsearch Restful API案例

The best elasticsearch highlevel java rest api-----bboss

Spring boot集成Elasticsearch Restful API案例分享, 本案例中代码兼容spring boot 1.x,2.x,兼容Elasticserch 1.x,2.x,5.x,6.x,以及后续版本。
本文中讲述的方法同样适用于其他xxx boot类型项目集成bboss es。
1.导入elasticsearch rest booter模块
maven工程
spring boot maven工程的pom.xml文件中导入以下maven坐标
        <dependency>
            <groupId>com.bbossgroups.plugins</groupId>
            <artifactId>bboss-elasticsearch-rest-booter</artifactId>
            <version>5.0.6.2</version>
        </dependency>

gradle工程
spring boot gradle工程的build.gradle文件中导入以下gradle坐标
compile "com.bbossgroups.plugins:bboss-elasticsearch-rest-booter:5.0.6.2"

2.配置elasticsearch地址
默认情况下,如果就是本机的elasticsearch服务器,导入bboss后不需要做任何配置就可以通过bboss rest api访问和操作elasticsearch。

极简单配置,修改spring boot项目的application.properties文件,只需要加入以下内容即可:
elasticsearch.rest.hostNames=10.21.20.168:9200
## 集群地址用逗号分隔
#elasticsearch.rest.hostNames=10.180.211.27:9280,10.180.211.27:9281,10.180.211.27:9282

如果需要更多的配置,可以将以下内容复制到spring boot项目的application.properties文件中:
#x-pack认证账号和口令
elasticUser=elastic
elasticPassword=changeme

#es服务器地址配置

elasticsearch.rest.hostNames=127.0.0.1:9200
#elasticsearch.rest.hostNames=10.180.211.27:9280,10.180.211.27:9281,10.180.211.27:9282

#动态索引表名称日期格式配置
elasticsearch.dateFormat=yyyy.MM.dd

elasticsearch.timeZone=Asia/Shanghai
elasticsearch.ttl=2d

#在控制台输出脚本调试开关showTemplate,false关闭,true打开,同时log4j至少是info级别
elasticsearch.showTemplate=true

#客户端动态发现es集群节点控制开关
elasticsearch.discoverHost=true

#http链接池配置
http.timeoutConnection = 400000
http.timeoutSocket = 400000
http.connectionRequestTimeout=400000
http.retryTime = 1
http.maxLineLength = -1
http.maxHeaderCount = 200
http.maxTotal = 400
http.defaultMaxPerRoute = 200

这些配置的含义,可以参考文档:《 高性能elasticsearch ORM开发库使用介绍》章节2进行了解。

其他各种boot框架配置的时候,也可自行创建application.properties配置文件,在其中配置需要的参数。

3.验证集成是否成功
完成前面两步工作后,就可以通过以下代码验证集成是否成功,如果正确打印elasticssearch集群状态,那说明集成成功:
        //创建es客户端工具,验证环境
		ClientInterface clientUtil = ElasticSearchHelper.getRestClientUtil();
		//验证环境,获取es状态
		String response = clientUtil.executeHttp("_cluster/state?pretty",ClientInterface.HTTP_GET);
        System.out.println(response);

3.完整的demo实例工程
https://github.com/bbossgroups/eshelloword-booter

https://gitee.com/bbossgroups/eshelloword-booter

4.参考文档
https://my.oschina.net/bboss/blog/1556866

猜你喜欢

转载自yin-bp.iteye.com/blog/2420236