Spring Data ElasticSearch环境搭建与使用
1 Spring Data ElasticSearch概述
- Spring Data ElasticSearch 对原生的ElasticSearch 简化
- 特点
1)基于@Configuration配置,只要在yml文件中配置,项目中就可以使用。
2)工具类 ElasticsearchTemplate ES模板,类似通用mapper,通过对象操作ES。
3)提供持久层接口 Repository,相当于通过mapper。
2 环境搭建
- 步骤一: 修改Pom.xml文件,添加对应坐标
<!--es-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
- 步骤二: 修改yml文件,添加Elasticsearch相关配置
spring:
redis:
database: 1 #确定使用库
host: 127.0.0.1 #redis服务地址
port: 6379 #redis 端口号
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: 127.0.0.1:9300
- 步骤三: 编写测试
package com.czxy.changgou3.elasticsearch;
import com.czxy.changgou3.TestApplication;
import com.czxy.changgou3.vo.ESBook;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
/**
* @author [email protected]
* @version 1.0
* @date 2020/4/13
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class)
public class TestES {
@Test
public void demo01(){
System.out.println("嘿嘿嘿");
}
}
步骤四: 异常报错
Caused by: java.lang.IllegalStateException: availableProcessors is already set to [8], rejecting [8]
解决方案
package com.czxy.changgou3.config;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
* @author [email protected]
* @version 1.0
* @date 2020/4/13
*/
@Configuration
public class ESConfig {
@PostConstruct
public void init(){
System.setProperty("es.set.netty.runtime.available.processors","false");
}
}