Elastic Search 的底层是开源库 Lucene。但是Lucene的使用门槛比较高,必须自己写代码去调用它的接口。而Elastic Search的出现正是为了解决了这个问题,它是 Lucene 的封装,提供了 REST API 的操作接口,我们可以开箱即用。

环境

  • JDK版本:8
  • SpringBoot:2.x
  • ES版本:7.1.1

依赖

		<!--   集成es client,并排除低版本依赖(5.6)     -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.1.1</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</exclusion>
<exclusion>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.1.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.1.1</version>
</dependency>

配置

使用配置类配置,可以参考如下所示:

先创建一个builder,用于初始化ES client

public class EsClientBuilder {
private int connectTimeoutMillis = 1000;
private int socketTimeoutMillis = 30000;
private int connectionRequestTimeoutMillis = 500;
private int maxConnectPerRoute = 10;
private int maxConnectTotal = 30; private final List<HttpHost> httpHosts; private EsClientBuilder(List<HttpHost> httpHosts) {
this.httpHosts = httpHosts;
} public EsClientBuilder setConnectTimeoutMillis(int connectTimeoutMillis) {
this.connectTimeoutMillis = connectTimeoutMillis;
return this;
} public EsClientBuilder setSocketTimeoutMillis(int socketTimeoutMillis) {
this.socketTimeoutMillis = socketTimeoutMillis;
return this;
} public EsClientBuilder setConnectionRequestTimeoutMillis(int connectionRequestTimeoutMillis) {
this.connectionRequestTimeoutMillis = connectionRequestTimeoutMillis;
return this;
} public EsClientBuilder setMaxConnectPerRoute(int maxConnectPerRoute) {
this.maxConnectPerRoute = maxConnectPerRoute;
return this;
} public EsClientBuilder setMaxConnectTotal(int maxConnectTotal) {
this.maxConnectTotal = maxConnectTotal;
return this;
} public static EsClientBuilder build(List<HttpHost> httpHosts) {
return new EsClientBuilder(httpHosts);
} public RestHighLevelClient create() { HttpHost[] httpHostArr = httpHosts.toArray(new HttpHost[0]);
RestClientBuilder builder = RestClient.builder(httpHostArr); builder.setRequestConfigCallback(requestConfigBuilder -> {
requestConfigBuilder.setConnectTimeout(connectTimeoutMillis);
requestConfigBuilder.setSocketTimeout(socketTimeoutMillis);
requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeoutMillis);
return requestConfigBuilder;
}); builder.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.setMaxConnTotal(maxConnectTotal);
httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
return httpClientBuilder;
}); return new RestHighLevelClient(builder);
}
}

再交给spring容器管理:

@Configuration
public class ESConfig {
@Value("${elasticsearch.nodes}")
private List<String> nodes; @Value("${elasticsearch.schema}")
private String schema; @Value("${elasticsearch.max-connect-total}")
private Integer maxConnectTotal; @Value("${elasticsearch.max-connect-per-route}")
private Integer maxConnectPerRoute; @Value("${elasticsearch.connection-request-timeout-millis}")
private Integer connectionRequestTimeoutMillis; @Value("${elasticsearch.socket-timeout-millis}")
private Integer socketTimeoutMillis; @Value("${elasticsearch.connect-timeout-millis}")
private Integer connectTimeoutMillis; @Bean
public RestHighLevelClient getRestHighLevelClient() {
List<HttpHost> httpHosts = new ArrayList<>();
for (String node : nodes) {
try {
String[] parts = StringUtils.split(node, ":");
Assert.notNull(parts,"Must defined");
Assert.state(parts.length == 2, "Must be defined as 'host:port'");
httpHosts.add(new HttpHost(parts[0], Integer.parseInt(parts[1]), schema));
} catch (RuntimeException ex) {
throw new IllegalStateException(
"Invalid ES nodes " + "property '" + node + "'", ex);
}
} return EsClientBuilder.build(httpHosts)
.setConnectionRequestTimeoutMillis(connectionRequestTimeoutMillis)
.setConnectTimeoutMillis(connectTimeoutMillis)
.setSocketTimeoutMillis(socketTimeoutMillis)
.setMaxConnectTotal(maxConnectTotal)
.setMaxConnectPerRoute(maxConnectPerRoute)
.create();
}
}

再配置一下常用的配置:

#配置es
elasticsearch:
# 如果是cluster,application.yml的nodes设置多个ip:host逗号隔开即可。
nodes: 127.0.0.1:9200
schema: http
max-connect-total: 50
max-connect-per-route: 10
connection-request-timeout-millis: 500
socket-timeout-millis: 30000
connect-timeout-millis: 1000

使用

接下来我们测试一下配置是否生效,一个简单的验证送给大家,如下所示:

@Autowired
private RestHighLevelClient client;
@Test
public void test() throws IOException {
MainResponse info = client.info(RequestOptions.DEFAULT);
System.out.println(info.toString());
}

配置生效的话,就会返回Elastic Search的配置信息:包含当前节点、集群、版本等信息。

SpringBoot集成ES至此结束。

本文可转载,但需声明原文出处。 程序员小明,一个很少加班的程序员。欢迎关注微信公众号,获取更多优质文章。

「Elasticsearch」SpringBoot快速集成ES的更多相关文章

  1. 「技巧」如何快速安装 Sketch 插件

    Sketch拥有强大丰富的插件,但是这些插件天各一方,四处查找下载地址非常麻烦.这里提供一个技巧,通过一个入口可以安装各种插件,基本涵盖了市面上所有靠谱的插件. 准备 Sketch54 Runner ...

  2. 「Elasticsearch」ES重建索引怎么才能做到数据无缝迁移呢?

    背景 众所周知,Elasticsearch是⼀个实时的分布式搜索引擎,为⽤户提供搜索服务.当我们决定存储某种数据,在创建索引的时候就需要将数据结构,即Mapping确定下来,于此同时索引的设定和很多固 ...

  3. 【ShardingSphere技术专题】「ShardingJDBC」SpringBoot之整合ShardingJDBC实现分库分表(JavaConfig方式)

    前提介绍 ShardingSphere介绍 ShardingSphere是一套开源的分布式数据库中间件解决方案组成的生态圈,它由Sharding-JDBC.Sharding-Proxy和Shardin ...

  4. SpringBoot快速集成SpringBootAdmin管控台监控服务

    SpringBootAdmin是一个针对 Spring Boot 的 Actuator 接口进行 UI 美化封装的监控工具,它可以在列表中浏览所有被监控 spring-boot 项目的基本信息.详细的 ...

  5. springboot快速集成swagger

    今天技术总监说:小明,我们本次3.0改造,使用swagger2.0作为前后端分离的接口规范,它可以一键生成前后端的API,一劳永逸--小明:??? Spring Boot 框架是目前非常流行的微服务框 ...

  6. SpringBoot 快速集成 Elastic Job

    一.引入依赖 <dependency> <groupId>com.github.kuhn-he</groupId> <artifactId>elasti ...

  7. Note/Solution -「洛谷 P5158」「模板」多项式快速插值

    \(\mathcal{Description}\)   Link.   给定 \(n\) 个点 \((x_i,y_i)\),求一个不超过 \(n-1\) 次的多项式 \(f(x)\),使得 \(f(x ...

  8. SpringBoot图文教程8 — SpringBoot集成MBG「代码生成器」

    有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1「概念+ ...

  9. SpringBoot图文教程14—SpringBoot集成EasyExcel「上」

    有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1「概念+ ...

随机推荐

  1. wpf 全局异常捕捉+简单日志记录

    `namespace MyApp { /// /// App.xaml 的交互逻辑 /// public partial class App : Application { public App() ...

  2. Module not found: Can't resolve 'bootstrap/dist/css/bootstrap-theme.css' in 'C:\react-form-validation-demo\src'

      此错误是由配置错误.版本不匹配或引导安装损坏引起的.如果已经安装了引导程序和反应引导程序,则可以通过以下方式进行更改: npm install --save bootstrap@^4.0.0-al ...

  3. [MIT6.006] 4. Heaps and Heap Sort 堆,堆排序

    第4节课仍然是讲排序,但介绍的是一种很高效的堆排序. 在编程过程中,有时候会需要进行extrat_max的操作,即从一个数列里挨个抽取最大值并将其它从原数列中移除.而排序问题也可以看作是一个extra ...

  4. nginx&http 第三章 ngx 事件event epoll 处理

    1. epoll模块命令集 ngx_epoll_commands  epoll模块上下文 ngx_epoll_module_ctx  epoll模块配置 ngx_epoll_module static ...

  5. mysql 触发器的创建和使用

    什么是触发器 触发器(TRIGGER)是MySQL的数据库对象之一,从5.0.2版本开始支持.该对象与编程语言中的函数非常类似,都需要声明.执行等.但是触发器的执行不是由程序调用,也不是由手工启动,而 ...

  6. linux文件增删拷(touch/mkdir/cp/mv/rm)

    touch或>命令创建普通文件: [root@localhost test]# touch a  ---创建单个文件 [root@localhost test]# ls a [root@loca ...

  7. 面试阿里,字节跳动90%会被问到的Java异常面试题集,史上最全系列!

    Java异常架构与异常关键字 Java异常简介 Java异常是Java提供的一种识别及响应错误的一致性机制. Java异常机制可以使程序中异常处理代码和正常业务代码分离,保证程序代码更加优雅,并提高程 ...

  8. Django解决(1146, "Table 'd42.django_session' doesn't exist")方法

    执行 ./manage.py makemigrations sessions ./manage.py migrate sessions

  9. 快来,Boom 3D广播功能还能这样用

    Boom 3D不仅为用户提供了包括3D立体音效.古典音乐音效在内的多种音效增强功能,而且还为用户提供了广播功能.该广播功能不仅涵盖了国内广播节目,而且还涵盖了国际广播节目. Boom 3D的广播功能还 ...

  10. k8S 搭建集群

    k8S 搭建集群1:修改主机名称hostnamectl --static set-hostname masterhostnamectl --static set-hostname node1hostn ...