一、环境安装
1.es安装
下载地址:https://www.elastic.co/cn/downloads/past-releases/elasticsearch-7-3-1
选择对应版本下载。解压到文件夹。
双击 elasticsearch.bat 启动。
访问9200端口,启动成功。
2.安装可视化工具
本地安装node环境。
代码下载地址:https://github.com/mobz/elasticsearch-head
下载后解压并启动。
2.代码开发
1.添加依赖
<!--ES-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.3.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.3.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.3.1</version>
</dependency>
2.添加配置
配置文件
elasticsearch:
enabled: false
maxConn: 8
address: 127.0.0.1:9200
配置类
@Component
@Data
@ConfigurationProperties(prefix = "elasticsearch")
public class EsProperties {
private boolean enabled;
private int maxConn = 8;
private String address;
}
3.工具类
public class ESUtil {
private static Logger LOG = LoggerFactory.getLogger(ESUtil.class);
protected static RestHighLevelClient client;
/**
* Java High Level REST Client 初始化
*/
public ESUtil(String host, int port) {
if (client == null) {
client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(host, port, "http")));
}
}
public ESUtil(String address) {
if (client == null) {
List<HttpHost> httpHosts = new LinkedList<>();
String[] addressString = address.split(",");
for (String add : addressString) {
String[] ipPort = add.split(":");
String host = ipPort[0];
String port = ipPort[1];
Integer intPort = Integer.valueOf(port);
httpHosts.add(new HttpHost(host, intPort, "http"));
}
HttpHost[] hosts = new HttpHost[httpHosts.size()];
httpHosts.toArray