SpringBoot 集成ElasticSearch
添加pom.xml
<!-- elasticsearch jar start -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- elasticsearch jar end -->
项目右键,Maven—》Update project 下载jar包
新建elasticsearch配置类ElasticsearchConfig
导包
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.client.ClientConfiguration.TerminalClientConfigurationBuilder;
代码
@Configuration
public class ElasticsearchConfig {
// 集群地址 "localhost:9200", "localhost:9291"
@Value("${elasticsearch.uris}")
private String uris;
@Value("${elasticsearch.username}")
private String username;
@Value("${elasticsearch.password}")
private String password;
// 设置连接超时。默认值为10秒
@Value("${elasticsearch.connectTimeout}")
private Long connectTimeout;
// 设置套接字超时。默认值为5秒
@Value("${elasticsearch.socketTimeout}")
private Long socketTimeout;
@Bean
RestHighLevelClient client() {
TerminalClientConfigurationBuilder terminalClientConfigurationBuilder = ClientConfiguration.builder()
.connectedTo(uris); // 集群地址
// .usingSsl() // (可选)启用SSL
// .withProxy("localhost:8888") // (可选)设置代理
// .withPathPrefix("ela") // (可选)设置路径前缀,通常在不同的群集将某个反向代理置于后面时使用
// .withDefaultHeaders() // (可选)设置标题
// 设置连接超时。默认值为10秒
if(connectTimeout != null && connectTimeout != 0L) {
terminalClientConfigurationBuilder.withConnectTimeout(connectTimeout);
}
// 设置套接字超时。默认值为5秒
if(socketTimeout != null && socketTimeout != 0L) {
terminalClientConfigurationBuilder.withSocketTimeout(socketTimeout);
}
// 添加基本身份验证
if(StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
terminalClientConfigurationBuilder.withBasicAuth(username, password);
}
ClientConfiguration clientConfiguration = terminalClientConfigurationBuilder.build();
return RestClients.create(clientConfiguration).rest();
}
}
配置文件application.yml 中添加相关配置
elasticsearch:
uris: 127.0.0.1:9200
username:
password:
connectTimeout:
socketTimeout:
添加实体类
导包
import java.io.Serializable;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import com.fasterxml.jackson.annotation.JsonFormat;
代码
@Document(indexName = "discusspost")
public class DatasEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
@Field(format=DateFormat.date_time,index=false,type=FieldType.Date)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date createDate;
@Field(format=DateFormat.date_time,index=false,type=FieldType.Date)
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date modifyDate;
@Field(type = FieldType.Keyword)
private String deviceType;
@Field(type = FieldType.Text)
private String deviceSn;
@Field(type = FieldType.Text)
private String deviceMac;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String datas;
Get and Set 方法
}
注解
注解 | 参数 | 作用 |
---|---|---|
@Document | 在类级别应用,以指示该类是映射到数据库的候选对象 | |
indexName | 用于存储此实体的索引的名称 | |
type | 映射类型。如果未设置,则使用小写的类的简单名称(自4.0版弃用) | |
shards | 索引的分片数 | |
replicas | 索引的副本数 | |
refreshIntervall | 索引的刷新间隔。用于索引创建。默认值为“ 1s” | |
indexStoreType | 索引的索引存储类型。用于索引创建。默认值为“ fs” | |
createIndex | 配置是否在存储库引导中创建索引。默认值是true | |
versionType | 版本管理的配置。默认值为EXTERNAL | |
@Field | 在字段级别应用并定义字段的属性,大多数属性映射到各自的Elasticsearch映射定义 | |
name | 字段名称,它将在Elasticsearch文档中表示,如果未设置,则使用Java字段名称 | |
type | 字段类型,可以是Text,Integer,Long,Date,Float,Double,Boolean,Object,Auto,Nested,Ip,Attachment,Keyword之一 | |
index | 是否索引(默认:true) | |
store | 标记是否将原始字段值存储在Elasticsearch中,默认值为false | |
searchAnalyzer | 指定字段搜索时使用的分词器 | |
format | 以及日期类型的pattern定义。必须为日期类型定义 | |
@Id | ES文档要求的ID,必须添加 @Id 注解,实际项目中需要区分业务逻辑的ID | |
@JsonFormat | pattern | Json中String和Date转换的时间格式 |
添加Dao层
导包
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;
代码
@Component
public interface DatasMapper extends ElasticsearchRepository<DatasEntity,Long> {
}
添加Service层
接口
public interface DatasService {
/**
* 新增或修改
*/
public DatasEntity save(DatasEntity datas);
/**
* 修改,与 save 相比 为null的字段不会更新
*/
public int update(DatasEntity datas) throws IOException;
}
实现类
导包
import java.io.IOException;
import java.util.Map;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
代码
@Service
public class DatasServiceImpl implements DatasService {
@Autowired
private DatasMapper datasMapper;
@Qualifier("client")
@Autowired
private RestHighLevelClient restHighLevelClient;
@Override
public DatasEntity save(DatasEntity datas) {
return datasMapper.save(datas);
}
@Override
public int update(DatasEntity datas) throws IOException {
UpdateRequest request = new UpdateRequest("discusspost", datas.getId().toString());
request.timeout("1s");
request.doc(JSON.toJSONString(datas), XContentType.JSON);
UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT);
return updateResponse.status().getStatus();
}
}
添加Controller层
@Autowired
private DatasService datasService;
@PostMapping("/insertESDatas")
@ResponseBody
public Boolean insertESDatas(@RequestBody DatasEntity datasEntity) {
if(datasEntity != null) {
DatasEntity datas = datasService.save(datasEntity);
return datas != null;
}
return false;
}
@PostMapping("/updateESDatas")
@ResponseBody
public Boolean updateESDatas(@RequestBody DatasEntity datasEntity) {
try {
if(datasEntity != null) {
int datas = datasService.update(datasEntity);
System.out.println("==================================" + datas);
return (datas+"").equals("200");
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
启动
启动类,右键 Run As/Debug AS —》Java Application 启动项目
Debug AS启动可以打断点,其他与Run As无区别
可能出现的问题
Cannot create index: Timeout connecting to [/127.0.0.1:9200]
解决办法
查看Linux elasticsearch端口有没有打开
下面elasticsearch端口用9200代替
执行命令:
firewall-cmd --query-port=9200/tcp
ps:yes 表示开启;no 表示未开启
① 端口未开启
开启9200端口
执行命令:
firewall-cmd --zone=public --add-port=9200/tcp --permanent
firewall-cmd --reload
②端口已开启
查看elasticsearch进程是否正常
执行命令:
ps -ef | grep elasticsearch
– 没有进程
重启elasticsearch
执行命令:
./elasticsearch -d
– 有进程
请检查链接等配置是否正确
postman测试接口
kibana中查看elasticsearch是否有值
链接:http://127.0.0.1:5601/app/home#/
① 点击左上角的菜单图标
② 选择Management—》Dev Tools菜单
③ 输入命令查看elasticsearch是否有值
命令:/ 实体类@Document注解的indexName属性/ 实体类@Document注解的type属性/ id
执行:点击下图中的三角图标
结果:显示在右侧
参考博客:
https://blog.csdn.net/BiandanLoveyou/article/details/115773729
https://blog.csdn.net/wpw2000/article/details/115704320