当前位置:   article > 正文

Spring Boot整合ElasticSearch单/多集群案例

spring.elasticsearch.bboss.http
Spring Boot整合ElasticSearch单个集群和多个集群案例分享,本文涉及内容:
  • 导入spring boot elasticsearch starter
  • 单个es集群案例
  • 多个es集群案例

本文内容适合于:
  • spring boot 1.x,2.x
  • elasticsearch 1.x,2.x,5.x,6.x,+

1.导入spring boot elasticsearch starter
在spring boot项目中导入spring boot elasticsearch starter

maven工程
        <dependency>
            <groupId>com.bbossgroups.plugins</groupId>
            <artifactId>bboss-elasticsearch-spring-boot-starter</artifactId>
            <version>5.0.8.6</version>
        </dependency>

gradle工程
compile "com.bbossgroups.plugins:bboss-elasticsearch-spring-boot-starter:5.0.8.6"

2.创建spring boot启动类
新建Application类:
  1. package org.bboss.elasticsearchtest.springboot;
  2. import org.frameworkset.elasticsearch.ElasticSearchHelper;
  3. import org.frameworkset.elasticsearch.client.ClientInterface;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.boot.SpringApplication;
  7. import org.springframework.boot.autoconfigure.SpringBootApplication;
  8. import org.springframework.context.annotation.Bean;
  9. /**
  10. * @author yinbp [122054810@qq.com]
  11. *
  12. */
  13. @SpringBootApplication
  14. public class Application {
  15. private Logger logger = LoggerFactory.getLogger(Application.class);
  16. public static void main(String[] args) {
  17. SpringApplication.run(Application.class, args);
  18. }
  19. }

Application类中定义了一个main方法用来启动spring boot elasticsearch测试应用。

Application类将被用于启动下面两个测试用例:
  • 单es集群测试用例
  • 多es集群测试用例

定义elasticsearch rest client组件实列管理类ServiceApiUtil:
  1. package org.bboss.elasticsearchtest.springboot;
  2. /*
  3. * Copyright 2008 biaoping.yin
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. import org.frameworkset.elasticsearch.ElasticSearchHelper;
  18. import org.frameworkset.elasticsearch.client.ClientInterface;
  19. import org.springframework.stereotype.Service;
  20. /**
  21. * 管理es rest client组件实例
  22. */
  23. @Service
  24. public class ServiceApiUtil {
  25. /**
  26. * 获取操作默认的es集群的客户端工具组件
  27. * @return
  28. */
  29. public ClientInterface restClient(){
  30. return ElasticSearchHelper.getRestClientUtil();
  31. }
  32. /**
  33. * 获取操作默认的es集群的加载dsl配置文件的客户端工具组件
  34. * @return
  35. */
  36. public ClientInterface restDemoConfigClient(){
  37. return ElasticSearchHelper.getConfigRestClientUtil("esmapper/demo.xml");
  38. }
  39. /**
  40. * 获取操作logs的es集群的客户端工具组件
  41. * @return
  42. */
  43. public ClientInterface restClientLogs(){
  44. return ElasticSearchHelper.getRestClientUtil("logs");
  45. }
  46. /**
  47. * 获取操作logs的es集群的加载dsl配置文件的客户端工具组件
  48. * @return
  49. */
  50. public ClientInterface restConfigClientLogs(){
  51. return ElasticSearchHelper.getConfigRestClientUtil("logs","esmapper/demo.xml");
  52. }
  53. }

实列管理类ServiceApiUtil将被注入到后续的测试用例中。

3.单es集群配置和使用
3.1 配置单es集群
修改spring boot配置文件application.properties内容(yml格式配置文件参考下面的内容配置):
  1. ##ES集群配置
  2. spring.elasticsearch.bboss.elasticUser=elastic
  3. spring.elasticsearch.bboss.elasticPassword=changeme
  4. #elasticsearch.rest.hostNames=10.1.236.88:9200
  5. #elasticsearch.rest.hostNames=127.0.0.1:9200
  6. #elasticsearch.rest.hostNames=10.21.20.168:9200
  7. spring.elasticsearch.bboss.elasticsearch.rest.hostNames=10.21.20.168:9200
  8. #elasticsearch.rest.hostNames=10.180.211.27:9280,10.180.211.27:9281,10.180.211.27:9282
  9. spring.elasticsearch.bboss.elasticsearch.dateFormat=yyyy.MM.dd
  10. spring.elasticsearch.bboss.elasticsearch.timeZone=Asia/Shanghai
  11. spring.elasticsearch.bboss.elasticsearch.ttl=2d
  12. #在控制台输出脚本调试开关showTemplate,false关闭,true打开,同时log4j至少是info级别
  13. spring.elasticsearch.bboss.elasticsearch.showTemplate=true
  14. spring.elasticsearch.bboss.elasticsearch.discoverHost=false
  15. # dsl配置文件热加载扫描时间间隔,毫秒为单位,默认5秒扫描一次,<= 0时关闭扫描机制
  16. spring.elasticsearch.bboss.dslfile.refreshInterval = -1
  17. ##es client http连接池配置
  18. spring.elasticsearch.bboss.http.timeoutConnection = 400000
  19. spring.elasticsearch.bboss.http.timeoutSocket = 400000
  20. spring.elasticsearch.bboss.http.connectionRequestTimeout=400000
  21. spring.elasticsearch.bboss.http.retryTime = 1
  22. spring.elasticsearch.bboss.http.maxLineLength = -1
  23. spring.elasticsearch.bboss.http.maxHeaderCount = 200
  24. spring.elasticsearch.bboss.http.maxTotal = 400
  25. spring.elasticsearch.bboss.http.defaultMaxPerRoute = 200
  26. spring.elasticsearch.bboss.http.soReuseAddress = false
  27. spring.elasticsearch.bboss.http.soKeepAlive = false
  28. spring.elasticsearch.bboss.http.timeToLive = 3600000
  29. spring.elasticsearch.bboss.http.keepAlive = 3600000
  30. spring.elasticsearch.bboss.http.keystore =
  31. spring.elasticsearch.bboss.http.keyPassword =
  32. # ssl 主机名称校验,是否采用default配置,
  33. # 如果指定为default,就采用DefaultHostnameVerifier,否则采用 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
  34. spring.elasticsearch.bboss.http.hostnameVerifier =
  35. ## 数据库数据源配置,使用db-es数据导入功能时需要配置
  36. #spring.elasticsearch.bboss.db.name = test
  37. #spring.elasticsearch.bboss.db.user = root
  38. #spring.elasticsearch.bboss.db.password = 123456
  39. #spring.elasticsearch.bboss.db.driver = com.mysql.jdbc.Driver
  40. #spring.elasticsearch.bboss.db.url = jdbc:mysql://localhost:3306/bboss
  41. #spring.elasticsearch.bboss.db.usePool = false
  42. #spring.elasticsearch.bboss.db.validateSQL = select 1


单ES集群配置项都是以spring.elasticsearch.bboss开头。

3.2 单集群测试用例
编写es单集群测试用例BBossESStarterTestCase
  1. /*
  2. * Copyright 1999-2018 Alibaba Group Holding Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.bboss.elasticsearchtest.springboot;
  17. import org.frameworkset.elasticsearch.client.ClientInterface;
  18. import org.junit.Test;
  19. import org.junit.runner.RunWith;
  20. import org.springframework.beans.factory.annotation.Autowired;
  21. import org.springframework.boot.test.context.SpringBootTest;
  22. import org.springframework.test.context.junit4.SpringRunner;
  23. /**
  24. * 单集群演示功能测试用例,spring boot配置项以spring.elasticsearch.bboss开头
  25. * 对应的配置文件为application.properties文件
  26. * @author yinbp [122054810@qq.com]
  27. */
  28. @RunWith(SpringRunner.class)
  29. @SpringBootTest(classes = Application.class)
  30. public class BBossESStarterTestCase {
  31. @Test
  32. public void testBbossESStarter() throws Exception {
  33. // System.out.println(bbossESStarter);
  34. //验证环境,获取es状态
  35. String response = serviceApiUtil.restClient().executeHttp("_cluster/state?pretty",ClientInterface.HTTP_GET);
  36. System.out.println(response);
  37. //判断索引类型是否存在,false表示不存在,正常返回true表示存在
  38. boolean exist = serviceApiUtil.restClient().existIndiceType("twitter","tweet");
  39. //判读索引是否存在,false表示不存在,正常返回true表示存在
  40. exist = serviceApiUtil.restClient().existIndice("twitter");
  41. exist = serviceApiUtil.restClient().existIndice("agentinfo");
  42. }
  43. }

直接通过junit运行上述测试用例即可

4.多ES集群测试用例
4.1 配置多es集群
修改spring boot配置文件application-multi-datasource.properties,内容如下:
  1. ##多集群配置样例,如果需要做多集群配置,请将参照本文内容修改application.properties文件内容
  2. spring.elasticsearch.bboss.default.name = default
  3. ##default集群配配置
  4. spring.elasticsearch.bboss.default.elasticUser=elastic
  5. spring.elasticsearch.bboss.default.elasticPassword=changeme
  6. #elasticsearch.rest.hostNames=10.1.236.88:9200
  7. #elasticsearch.rest.hostNames=127.0.0.1:9200
  8. spring.elasticsearch.bboss.default.elasticsearch.rest.hostNames=10.21.20.168:9200
  9. #elasticsearch.rest.hostNames=10.180.211.27:9280,10.180.211.27:9281,10.180.211.27:9282
  10. spring.elasticsearch.bboss.default.elasticsearch.dateFormat=yyyy.MM.dd
  11. spring.elasticsearch.bboss.default.elasticsearch.timeZone=Asia/Shanghai
  12. spring.elasticsearch.bboss.default.elasticsearch.ttl=2d
  13. #在控制台输出脚本调试开关showTemplate,false关闭,true打开,同时log4j至少是info级别
  14. spring.elasticsearch.bboss.default.elasticsearch.showTemplate=true
  15. spring.elasticsearch.bboss.default.elasticsearch.discoverHost=false
  16. ##default连接池配置
  17. spring.elasticsearch.bboss.default.http.timeoutConnection = 400000
  18. spring.elasticsearch.bboss.default.http.timeoutSocket = 400000
  19. spring.elasticsearch.bboss.default.http.connectionRequestTimeout=400000
  20. spring.elasticsearch.bboss.default.http.retryTime = 1
  21. spring.elasticsearch.bboss.default.http.maxLineLength = -1
  22. spring.elasticsearch.bboss.default.http.maxHeaderCount = 200
  23. spring.elasticsearch.bboss.default.http.maxTotal = 400
  24. spring.elasticsearch.bboss.default.http.defaultMaxPerRoute = 200
  25. spring.elasticsearch.bboss.default.http.keystore =
  26. spring.elasticsearch.bboss.default.http.keyPassword =
  27. # ssl 主机名称校验,是否采用default配置,
  28. # 如果指定为default,就采用DefaultHostnameVerifier,否则采用 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
  29. spring.elasticsearch.bboss.default.http.hostnameVerifier =
  30. ##logs集群配置
  31. spring.elasticsearch.bboss.logs.name = logs
  32. spring.elasticsearch.bboss.logs.elasticUser=elastic
  33. spring.elasticsearch.bboss.logs.elasticPassword=changeme
  34. #elasticsearch.rest.hostNames=10.1.236.88:9200
  35. spring.elasticsearch.bboss.logs.elasticsearch.rest.hostNames=127.0.0.1:9200
  36. #elasticsearch.rest.hostNames=10.21.20.168:9200
  37. #elasticsearch.rest.hostNames=10.180.211.27:9280,10.180.211.27:9281,10.180.211.27:9282
  38. spring.elasticsearch.bboss.logs.elasticsearch.dateFormat=yyyy.MM.dd
  39. spring.elasticsearch.bboss.logs.elasticsearch.timeZone=Asia/Shanghai
  40. spring.elasticsearch.bboss.logs.elasticsearch.ttl=2d
  41. #在控制台输出脚本调试开关showTemplate,false关闭,true打开,同时log4j至少是info级别
  42. spring.elasticsearch.bboss.logs.elasticsearch.showTemplate=true
  43. spring.elasticsearch.bboss.logs.elasticsearch.discoverHost=false
  44. ##logs集群对应的连接池配置
  45. spring.elasticsearch.bboss.logs.http.timeoutConnection = 400000
  46. spring.elasticsearch.bboss.logs.http.timeoutSocket = 400000
  47. spring.elasticsearch.bboss.logs.http.connectionRequestTimeout=400000
  48. spring.elasticsearch.bboss.logs.http.retryTime = 1
  49. spring.elasticsearch.bboss.logs.http.maxLineLength = -1
  50. spring.elasticsearch.bboss.logs.http.maxHeaderCount = 200
  51. spring.elasticsearch.bboss.logs.http.maxTotal = 400
  52. spring.elasticsearch.bboss.logs.http.defaultMaxPerRoute = 200
  53. # https证书配置
  54. spring.elasticsearch.bboss.logs.http.keystore =
  55. spring.elasticsearch.bboss.logs.http.keyPassword =
  56. # ssl 主机名称校验,是否采用default配置,
  57. # 如果指定为default,就采用DefaultHostnameVerifier,否则采用 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
  58. spring.elasticsearch.bboss.logs.http.hostnameVerifier =
  59. # dsl配置文件热加载扫描时间间隔,毫秒为单位,默认5秒扫描一次,<= 0时关闭扫描机制
  60. spring.elasticsearch.bboss.dslfile.refreshInterval = -1

配置说明:

上面配置了两个集群:default和logs

每个集群配置项的前缀为:spring.elasticsearch.bboss.集群名字,其中的集群名字是一个自定义的逻辑名称,用来在client api中引用集群。

default集群的配置项前缀为:

spring.elasticsearch.bboss.default
logs集群的配置项前缀为:

spring.elasticsearch.bboss.logs
同时每个集群的配置项目里面必须包含name项目的配置

default集群name配置:

spring.elasticsearch.bboss.default.name = default
logs集群name配置:

##logs集群配置
spring.elasticsearch.bboss.logs.name = logs
4.2 定义加载多es集群配置的spring boot Configuration类
新建类MultiESSTartConfigurer
  1. package org.bboss.elasticsearchtest.springboot;
  2. /*
  3. * Copyright 2008 biaoping.yin
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. import org.frameworkset.elasticsearch.ElasticSearchHelper;
  18. import org.frameworkset.elasticsearch.boot.BBossESStarter;
  19. import org.frameworkset.elasticsearch.client.ClientInterface;
  20. import org.springframework.boot.context.properties.ConfigurationProperties;
  21. import org.springframework.context.annotation.Bean;
  22. import org.springframework.context.annotation.Configuration;
  23. import org.springframework.context.annotation.Primary;
  24. import org.springframework.context.annotation.Profile;
  25. /**
  26. * 配置多个es集群
  27. * 指定多es数据源profile:multi-datasource
  28. */
  29. @Configuration
  30. @Profile("multi-datasource")
  31. public class MultiESSTartConfigurer {
  32. @Primary
  33. @Bean(initMethod = "start")
  34. @ConfigurationProperties("spring.elasticsearch.bboss.default")
  35. public BBossESStarter bbossESStarterDefault(){
  36. return new BBossESStarter();
  37. }
  38. @Bean(initMethod = "start")
  39. @ConfigurationProperties("spring.elasticsearch.bboss.logs")
  40. public BBossESStarter bbossESStarterLogs(){
  41. return new BBossESStarter();
  42. }
  43. }

说明:

MultiESSTartConfigurer通过以下两个方法分别加载default和logs两个es集群的配置

default集群配置加载
  1. @Primary
  2. @Bean(initMethod = "start")
  3. @ConfigurationProperties("spring.elasticsearch.bboss.default")
  4. public BBossESStarter bbossESStarterDefault()
  5. logs集群配置加载
  6. @Bean(initMethod = "start")
  7. @ConfigurationProperties("spring.elasticsearch.bboss.logs")
  8. public BBossESStarter bbossESStarterLogs()

4.3 定义多es集群测试用例
多es集群测试用例MultiBBossESStartersTestCase
  1. package org.bboss.elasticsearchtest.springboot;
  2. import org.frameworkset.elasticsearch.client.ClientInterface;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.test.context.ActiveProfiles;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. /**
  10. * 多集群演示功能测试用例,spring boot配置项以spring.elasticsearch.bboss.集群名称开头,例如:
  11. * spring.elasticsearch.bboss.default 默认es集群
  12. * spring.elasticsearch.bboss.logs logs es集群
  13. * 两个集群通过 org.bboss.elasticsearchtest.springboot.MultiESSTartConfigurer加载
  14. * 对应的配置文件为application-multi-datasource.properties文件
  15. * 通过ActiveProfiles指定并激活多es集群配置:multi-datasource
  16. * @author yinbp [122054810@qq.com]
  17. */
  18. @RunWith(SpringRunner.class)
  19. @SpringBootTest(classes = Application.class)
  20. @ActiveProfiles("multi-datasource")
  21. public class MultiBBossESStartersTestCase {
  22. @Test
  23. public void testMultiBBossESStarters() throws Exception {
  24. //验证环境,获取es状态
  25. String response = serviceApiUtil.restClient().executeHttp("_cluster/state?pretty",ClientInterface.HTTP_GET);
  26. System.out.println(response);
  27. //判断索引类型是否存在,false表示不存在,正常返回true表示存在
  28. boolean exist = serviceApiUtil.restClientLogs().existIndiceType("twitter","tweet");
  29. System.out.println("twitter/tweet:"+exist);
  30. //判读索引是否存在,false表示不存在,正常返回true表示存在
  31. exist = serviceApiUtil.restClientLogs().existIndice("twitter");
  32. System.out.println("twitter:"+exist);
  33. exist = serviceApiUtil.restClientLogs().existIndice("agentinfo");
  34. System.out.println("agentinfo:"+exist);
  35. }
  36. }

直接通过junit运行上述测试用例即可。

5.完整的demo工程
https://gitee.com/bbossgroups/eshelloword-spring-boot-starter

https://github.com/bbossgroups/eshelloword-spring-boot-starter

6 开发交流

elasticsearch微信公众号:
img_a21db47cf20ac4820026d60bcb2b9470.jpe

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/500513
推荐阅读
相关标签
  

闽ICP备14008679号