目录
版本说明:
开始代码
maven依赖:
配置yml:
连接es配置文件:
开发查询接口
新增对象
新增查询工具类
新增查询service
新增查询接口
测试结果编辑
ES8官方api资料不全,先用了springboot自带的jar做连接,结果失败了,后来才知道es7以后就不支持template的连接方式,自己踩了不少坑,这里参考官方的api做了一个demo,供各位大佬参考,有哪里不对的欢迎各路大神批评指正
api地址:
Connecting | Elasticsearch Java API Client [8.1] | Elastichttps://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/connecting.html
版本说明:
springboot:2.1.8-RELEASE
ElasticSearch: 8.1(非集群)
JDK: 1.8
开发工具:IDEA
框架:springboot+mybatisplus
数据库:mysql 5.7
开始代码
springboot和ElasticSearch搭建步骤就省略了
maven依赖:
springboot的2.1.8-RELEASE版本不支持8.1版本的es,因此直接使用官方推荐的maven依赖包
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.1.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>8.1.2</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.json</artifactId>
<version>2.0.1</version>
</dependency>
配置yml:
因为后面要自己写代码连接es,这里配置自己加了一些东西,es在搭建的时候设置了登陆认证
spring:
elasticsearch:
rest:
# 是否启用es
enable: false
uris: 127.0.0.1:9200
host: 127.0.0.1
port: 9200
username: elastic
password: 123456
连接es配置文件:
@Configuration
public class ElasticSearchConfig {
@Value("${spring.elasticsearch.rest.host}")
private String host;
@Value("${spring.elasticsearch.rest.enable:true}")
private boolean enable;
@Value("${spring.elasticsearch.rest.port}")
private int port;
@Value("${spring.elasticsearch.rest.username}")
private String userName;
@Value("${spring.elasticsearch.rest.password}")
private String passWord;
//注入IOC容器
@Bean
public ElasticsearchClient elasticsearchClient(){
ElasticsearchClient client = new ElasticsearchClient(null);
if (enable){
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//设置账号密码
credentialsProvider.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials(userName, passWord));
// RestClients restClients =
RestClient restClient = RestClient.builder(new HttpHost(host, port))
.setHttpClientConfigCallback(httpClientBuilder->httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
// And create the API client
client = new ElasticsearchClient(transport);
}
return client;
}
}
这时候可以启动代码监控下日志,看是否连接成功es
开发查询接口
统一返回结果对象
/**
* 响应数据
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@ApiModel(value = "响应")
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 编码:0表示成功,其他值表示失败
*/
@ApiModelProperty(value = "编码:0表示成功,其他值表示失败 2表示有弱提醒")
@JsonProperty("Code")
public int Code = 0;
/**
* 消息内容
*/
@ApiModelProperty(value = "消息内容")
@JsonProperty("Message")
public String Message = "操作成功";
/**
* 是否成功
*/
@ApiModelProperty(value = "是否成功")
@JsonProperty("Success")
public boolean Success = true;
/**
* 响应数据
*/
@ApiModelProperty(value = "响应数据")
public T Response;
public Result<T> ok(T Response) {
this.Response = Response;
return this;
}
public Result<T> ok() {
this.Response = null;
return this;
}
public Result<T> ok(T Response,String message) {
this.Response = Response;
this.Message = message;
return this;
}
public boolean success() {
return Code == 0 ? true : false;
}
public Result<T> error() {
this.Success = false;
this.Code = 500;
this.Message = "系统错误";
return this;
}
public Result<T> error(int code) {
this.Success = false;
this.Code = code;
return this;
}
public Result<T> error(int code, String Message) {
this.Success = false;
this.Code = code;
this.Message = Message;
return this;
}
public Result<T> error(String Message) {
this.Success = false;
this.Code = 500;
this.Message = Message;
return this;
}
public static Result OK() {
return new Result(0,"操作成功",null);
}
public static Result OK(Object rtnData) {
return new Result(0,"操作成功",rtnData);
}
public static Result TIP(Object rtnData,String message) {
return new Result(2,message,rtnData);
}
public static Result OK(Object rtnData,String message) {
return new Result(0,message,rtnData);
}
public static Result rtn(Integer code, String Message, Object rtnData) {
return new Result(1,Message,rtnData);
}
public static Result ERROR(String Message) {
return new Result(1,Message,null);
}
public static Result ERROR(Integer code,String Message) {
return new Result(code,Message,null);
}
public Result(int code, String message, T response) {
Code = code;
Message = message;
Response = response;
Success = code == 0?true:false;
}
public Result() {
}
}
新增对象
业务对象实体:
@Data
@Accessors(chain = true)
public class HdiotDecodeDTO {
private String appid;
private String pid;
private String drvid;
private String map_devid;
private String pcode;
private String protocol;
private String devid;
private String sn;
private String imei;
private String messageid;
private Object data;
private String session;
private Date created;
private Date changed;
@Override
public String toString() {
return "HdiotDecodeBean{" +
"appid='" + appid + '\'' +
", pid='" + pid + '\'' +
", drvid='" + drvid + '\'' +
", devid='" + devid + '\'' +
", sn='" + sn + '\'' +
", imei='" + imei + '\'' +
", messageid='" + messageid + '\'' +
", data=" + data +
", session='" + session + '\'' +
", created=" + created +
", changed=" + changed +
'}';
}
}
查询对象实体:
@Data
public class EsQueryDTO {
@ApiModelProperty("索引名称")
private String indexName;
@ApiModelProperty("关键字属性")
private String field;
@ApiModelProperty("关键字")
private String word;
@ApiModelProperty("起始行")
private Integer from;
@ApiModelProperty("页数")
private Integer size;
public Integer getSize() {
return size==0?30:size;
}
}
新增查询工具类
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.CountResponse;
import co.elastic.clients.elasticsearch.core.GetResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.alibaba.fastjson.JSON;
import com.hdkj.hdiot.configure.common.PageData;
import com.hdkj.hdiot.configure.es.bean.EsQueryDTO;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.ss.formula.functions.T;
import java.io.IOException;
import java.util.*;
/**
* @author liuch
* @title: ElasticClientUtils
* @description: TODO
* @date 2022/4/2 9:50
*/
public class ElasticClientUtils<T> {
/**
* @author liuch
* @description 根据关键字分页查询
* @date 2022/4/2 17:15
* @param
* @param client
* @param dto
* @param target
* @return java.util.List<T>
*/
public List<T> queryByFiled(ElasticsearchClient client, EsQueryDTO dto,Class<T> target) throws Exception {
List<T> result = new ArrayList<>();
SearchResponse<HashMap> search = client.search(s -> s
.index(dto.getIndexName())
.query(q -> q.term(t -> t
.field(dto.getField())
.value(dto.getWord())
)).from(dto.getFrom()).size(dto.getSize()),
HashMap.class);
List<Hit<HashMap>> hits = search.hits().hits();
Iterator<Hit<HashMap>> iterator = hits.iterator();
while (iterator.hasNext()){
Hit<HashMap> decodeBeanHit = iterator.next();
Map<String,Object> docMap = decodeBeanHit.source();
String json = JSON.toJSONString(docMap);
T obj = JSON.parseObject(json,target);
result.add(obj);
}
return result;
}
/**
* @author liuch
* @description 根据关键字查询总条数
* @date 2022/4/2 17:15
* @param
* @param client
* @param dto
* @return long
*/
public long queryCountByFiled(ElasticsearchClient client, EsQueryDTO dto) throws Exception {
CountResponse count = client.count(c -> c.index(dto.getIndexName()).query(q -> q.term(t -> t
.field(dto.getField())
.value(dto.getWord())
)));
long total = count.count();
return total;
}
/**
* @author liuch
* @description 查询分页信息
* @date 2022/4/2 17:16
* @param
* @param client
* @param dto
* @param target
* @return com.hdkj.hdiot.configure.common.PageData<T>
*/
public PageData<T> queryPageByFiled(ElasticsearchClient client, EsQueryDTO dto,Class<T> target) throws Exception {
long total = queryCountByFiled(client,dto);
List<T> result = queryByFiled(client,dto,target);
PageData<T> pageData = new PageData<>(result,total);
return pageData;
}
/**
* @author liuch
* @description 根据文档id查询
* @date 2022/4/2 17:16
* @param
* @param client
* @param dto
* @param target
* @return java.lang.Object
*/
public Object queryByDocumentId(ElasticsearchClient client, EsQueryDTO dto,Class<T> target) throws Exception {
GetResponse<HashMap> getResponse = client.get(s -> s
.index(dto.getIndexName()).id(dto.getWord()),
HashMap.class);
getResponse.source();
Map<String,Object> docMap = getResponse.source();
String json = JSON.toJSONString(docMap);
T obj = JSON.parseObject(json,target);
return obj;
}
}
新增查询service
public interface HdiotDecodeService {
Result getDecodeMsg(EsQueryDTO dto);
}
实现类:
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.hdkj.hdiot.configure.common.PageData;
import com.hdkj.hdiot.configure.common.Result;
import com.hdkj.hdiot.configure.es.bean.EsQueryDTO;
import com.hdkj.hdiot.configure.es.bean.HdiotDecodeDTO;
import com.hdkj.hdiot.configure.es.bean.HdiotOriginalDTO;
import com.hdkj.hdiot.configure.es.service.HdiotDecodeService;
import com.hdkj.hdiot.configure.es.utils.ElasticClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author liuch
* @title: HdiotDecodeServiceImpl
* @description: TODO
* @date 2022/4/1 11:39
*/
@Service
public class HdiotDecodeServiceImpl implements HdiotDecodeService {
@Autowired
private ElasticsearchClient client;
/**
* @author liuch
* @description 查询原始数据
* @date 2022/4/2 10:56
* @param
* @param dto
* @return com.hdkj.hdiot.configure.common.Result
*/
@Override
public Result getDecodeMsg(EsQueryDTO dto) {
// decode_data origin_data
try {
dto.setIndexName("decode_data");
dto.setField("devid");
PageData<HdiotDecodeDTO> pageData = new ElasticClientUtils<HdiotDecodeDTO>().queryPageByFiled(client,dto,HdiotDecodeDTO.class);
return new Result().ok(pageData);
} catch (Exception e) {
e.printStackTrace();
return new Result().error(e.getMessage());
}
}
}
新增查询接口
@Autowired
HdiotDecodeService decodeService;
@PostMapping(value = "/decodeMsg")
public Result getDecodeMsg(@RequestBody EsQueryDTO dto){
return decodeService.getDecodeMsg(dto);
}
测试结果
其他文章推荐:
springboot + mybatis启动时执行sql脚本_大师兄小灰灰的博客-CSDN博客springboot + mybatis启动时执行sql脚本https://blog.csdn.net/qq_24473507/article/details/126094224
linux安装nginx_大师兄小灰灰的博客-CSDN博客系统环境:CentOs7.9nginx下载地址:nginx: download前期准备安装依赖程序包:1.先安装gcc-c++编译器yum install -y gcc-c++ yum install -y openssl openssl-devel 2.再安装pcre包yum install -y pcre pcre-devel3.再安装zlib包yum install -y zlib zlib-devel下面进行nginx的安装下载并解压.https://blog.csdn.net/qq_24473507/article/details/121973007
发文助手提醒我:
文章质量提示
- 此文章质量较低,不会获得较多流量扶持! 可能的原因为:篇幅太短,广告涉嫌违规,外链过多,缺少代码,图片涉嫌违规。
请问要怎么样才能满足csdn的要求呢?搞一万字?文章来源:https://uudwc.com/A/L5ZV
————————————————
版权声明:本文为CSDN博主「大师兄小灰灰」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_24473507/article/details/123924463文章来源地址https://uudwc.com/A/L5ZV