引入elasticsearch包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
application.yml中的elasticsearch配置
spring:
data:
elasticsearch:
cluster-nodes: 127.0.0.1:9300 #配置es节点信息,逗号分隔
cluster-name: elasticsearch #默认即为 elasticsearch
properties:
transport:
tcp:
connect_timeout: 60s
path:
logs: ./elasticsearch/log #elasticsearch日志存储目录
data: ./elasticsearch/data #elasticsearch数据存储目录
CURD操作方式:
public interface TestModelService2 extends ElasticsearchRepository<TestModel, String>
启动过程出现错误:
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.lang.Object org.springframework.data.elasticsearch.repository.ElasticsearchRepository.index(java.lang.Object)! No property index found for type TestModel!
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property index found for type TestModel!
集成前提是:系统中已有对数据库的CURD操作,然后想加入elasticsearch搜索功能,操作的实体既是entity对象,也是document对象
错误的大概意思是说:org.springframework.data.elasticsearch.repository.ElasticsearchRepository 类中的index方法,系统按照JPA操作数据库的方式,认为index方法是通过index字段查找数据,然而,实体中没有index字段,所以就出错了
错误的原因是:
@EntityScan("com.bc")和
@ComponentScan
(
"com.bc"
)注解扫描到了该类,导致系统以为是数据库操作类,然后按数据库的实现类进行注入
解决办法:
@EnableElasticsearchRepositories
(
basePackages
=
"com.search"
)区分不同包扫描,将crud操作类放到该包的子包下
其他错误:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.transport.TransportClient]: Factory method 'elasticsearchClient' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [8], rejecting [8]
加入启动参数,代码中:
static{
System.setProperty("es.set.netty.runtime.available.processors", "false");
}
或是在jvm启动参数:
-Des.set.netty.runtime.available.processors=false