Springboot整合Elasticsearch
首先,我们需要先创建一个SpringBoot项目,可参考我之前编写的SpringBoot项目的创建
1、导入相关maven依赖
<!--elasticsearch检索服务依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2、创建yml配置文件

server: port: 8080 elasticsearch: esSchema: http esAddress: 192.168.111.129 #你的服务器地址 esPort: 9200 esUserName: elastic #账号 esPassword: elastic #你的elasticsearch密码
3、创建config配置文件

注意这里导入的是ES的client依赖
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchClientConfig {
@Value("${elasticsearch.esUserName}")
private String userName;
@Value("${elasticsearch.esPassword}")
private String password;
@Value("${elasticsearch.esAddress}")
private String hostName;
@Value("${elasticsearch.esPort}")
private Integer port;
@Value("${elasticsearch.esSchema}")
private String scheme;
public static RestHighLevelClient client = null;
@Bean
public RestHighLevelClient restHighLevelClient() {
//不需要用户名和密码的认证
//client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", "9300", "http")));
//需要用户名和密码的认证
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(hostName, port, scheme))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
client = new RestHighLevelClient(restClientBuilder);
return client;
}
}
4、创建实体类
创建一个实体类供ES插入文档时使用

import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class User {
private String name;
private String age;
}
5、编写测试类

import com.alibaba.fastjson.JSON;
import com.chen.elastic.pojo.User;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
class ElasticApplicationTests {
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
/**
* 索引的创建,所有的请求都是用Request
*/
@Test
void contextLoads() throws IOException {
//创建索引的请求
CreateIndexRequest request = new CreateIndexRequest("chen_index");
//执行请求
CreateIndexResponse createIndexRequest = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexRequest);
}
/**
* 获取索引
*/
@Test
void testExistIndex() throws IOException {
GetIndexRequest request= new GetIndexRequest("chen_index");
boolean exists = client.indices().exists(request,RequestOptions.DEFAULT);
System.out.println(exists);
}
/**
* 删除索引
*/
@Test
void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("chen_index");
AcknowledgedResponse delete = client.indices().delete(request,RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
/**
* 创建文档
*/
@Test
void testAddDocument() throws IOException {
User user = new User("CJZ","3");
IndexRequest request= new IndexRequest("chen_index");
//ES中的_id为1
request.id("1");
request.timeout("1s");
//将数据放入请求
request.source(JSON.toJSONString(user), XContentType.JSON);
//客户端发送请求
IndexResponse indexResponse = client.index(request,RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
System.out.println(indexResponse.status());
}
}
原创文章,作者:端木书台,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/245154.html