1.新建springboot工程,增加es依赖和配置
pom.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.cz</groupId>
<artifactId>springboot_es_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_es_demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<elasticsearch>7.12.1</elasticsearch>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client-sniffer</artifactId>
<version>${elasticsearch}</version>
</dependency>
<!--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
springboot版本2.5.4,对应的spring-boot-starter-data-elasticsearch为4.2.4,而对应的elasticsearch-client为7.12.1
application.yml增加配置:
spring:
elasticsearch:
rest:
uris: 192.168.220.136:9200
sniffer:
interval: 5000ms
delay-after-failure: 15000ms
uris为es连接地址,和elasticsearch-head-master连接地址一样
当然spring.elasticsearch.rest还有其他属性,可以根据实际情况设置
?2.编写controller获取es信息
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.cluster.ClusterHealth;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/es")
public class EsLogController {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
@GetMapping("/getEsInfo")
public ClusterHealth getEsInfo() {
return elasticsearchRestTemplate.cluster().health();
}
}
利用ElasticsearchRestTemplate的实体对es进行操作,然后也可以使用RestHighLevelClient对象来进行操作,如上为获取集群信息
3.启动项目,验证结果
启动后
?可以看到有一条警告,因为我客户端使用版本为7.12.1,es版本为7.13.2,但目前使用还没发现有什么问题,待验证
浏览器输入http://localhost:8080/es/getEsInfo结果为:
{ ? "clusterName": "my_elasticsearch", ? "status": "GREEN", ? "numberOfNodes": 3, ? "numberOfDataNodes": 3, ? "activeShards": 36, ? "relocatingShards": 0, ? "activePrimaryShards": 16, ? "initializingShards": 0, ? "unassignedShards": 0, ? "activeShardsPercent": 100.0, ? "numberOfPendingTasks": 0, ? "timedOut": false, ? "numberOfInFlightFetch": 0, ? "delayedUnassignedShards": 0, ? "taskMaxWaitingTimeMillis": 0 }
clusterName为es集群名称,status为集群状态,总三个节点
4.操作es
对于es的操作可以注入ElasticsearchRestTemplate来操作,也可以使用ElasticsearchRepository来操作
1.创建实体类
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.*;
import java.io.Serializable;
import java.util.Date;
@Data
@Document(indexName = "log")
@Setting(shards = 1, replicas = 2)
public class EsLog implements Serializable{
private static final long serialVersionUID = 1L;
@Id
private String id;
private String createBy;
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@Field(type = FieldType.Date, index = false, format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime = new Date();
private Long timeMillis = System.currentTimeMillis();
private String updateBy;
private Integer delFlag;
@Field(type = FieldType.Text)
private String name;
private Integer logType;
private String requestUrl;
private String requestType;
private String requestParam;
private String username;
private String ip;
private String ipInfo;
private Integer costTime;
}
对于注解@Document,主要需要设置indexName,即索引名称,es新建索引还有其他两个主要属性,分片数和副本数,这个在@Document默认为1,切过时了,看源码可知,需在@Setting中设置
?这里节点为3个,所以@Setting(shards = 1, replicas = 2),所以副本为2
注解@Document中还有两个属性createIndex和useServerConfiguration
createIndex=true时,表示当Spring应用程序启动时,如果配置的索引不存在,则Spring会创建索引
useServerConfiguration=true时,当Spring创建索引时,Spring不会在创建的索引中设置以下设置:shards,replicas,refreshInterval和indexStoreType.这些设置将是Elasticsearch默认值
通过源码可以看到createIndex默认为true,useServerConfiguration默认为false,重新启动后可以通过head插件看到多了log索引
注解@Field相当于数据库字段,主要有name(字段名称)和tyep(字段类型)属性
?
?Document相当于数据库一行记录,index相当于表名
2.创建dao
import com.cz.springboot_es_demo.entity.EsLog;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface EsLogDao extends ElasticsearchRepository<EsLog, String> {
}
?ElasticsearchRepository<T, ID>中T为实体类型,ID为id的类型,这里id为String类型
3.操作
1.添加到es
@Autowired
private EsLogDao logDao;
@PostMapping("/save")
public EsLog save() {
EsLog log = new EsLog();
return logDao.save(log);
}
2.通过ID查询
@GetMapping("/findOne/{id}")
public EsLog findOne(@PathVariable("id") String id) {
return logDao.findById(id).get();
}
3.分页查询
@GetMapping("/findPage")
public SearchHits<EsLog> findPage() {
Long start = DateUtil.parse("2021-09-21 21:00:00").getTime();
Long end = DateUtil.endOfDay(DateUtil.parse("2021-09-21 22:00:00")).getTime();
Pageable pageable = PageRequest.of(0, 2, Sort.by(Sort.Direction.DESC, "createTime"));
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("name").is("查询"));
criteriaQuery.addCriteria(new Criteria("timeMillis").between(start, end));
criteriaQuery.setPageable(pageable);
SearchHits<EsLog> searchHits = elasticsearchRestTemplate.search(criteriaQuery, EsLog.class);
return searchHits;
}
|