springmvc + spring-data-elasticsearch 踩坑指南
环境
ElasticSearch 6.8.6(我用的是docker安装版)
大坑(版本问题, 版本不对会出现各种ClassNotFound)
-
查看对应版本(这里我们以
6.8.6
为例子 )https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#repositories
Spring Data Release Train | Spring Data Elasticsearch | Elasticsearch | Spring Boot |
---|---|---|---|
Neumann | 4.0.x | 7.6.2 | 2.3.x |
Moore | 3.2.x | 6.8.6 | 2.2.x |
Lovelace | 3.1.x | 6.2.2 | 2.1.x |
Kay | 3.0.x | 5.5.0 | 2.0.x |
Ingalls | 2.1.x | 2.4.0 | 1.5.x |
-
我们这边使用springmvc, 需要去查询对应springboot版本对应的spring版本
2.3.1 CURRENT GA | Reference Doc. | API Doc. |
---|---|---|
2.4 SNAPSHOT | Reference Doc. | API Doc. |
2.3.2 SNAPSHOT | Reference Doc. | API Doc. |
2.2.9 SNAPSHOT | Reference Doc. | API Doc. |
2.2.8 GA | Reference Doc. | API Doc. |
2.1.16 SNAPSHOT | Reference Doc. | API Doc. |
2.1.15 GA | Reference Doc. | API Doc. |
-
点击对应版本的
Reference Doc
https://docs.spring.io/spring-boot/docs/2.2.9.BUILD-SNAPSHOT/reference/html/
-
我们现在确定了
spring
的版本, 接下来确定spring-data-elasticsearch
版本https://mvnrepository.com/artifact/org.springframework.data/spring-data-elasticsearch
之前我们已经确定了版本是3.2.x, 现在就来确定具体版本号, 我们随便点开一个进去
可以看到ElasticSearch版本是6.8.10
至此, 我们就能得到spring版本和 spring-data-elasticsearch 版本号了
小坑
使用网上说的xml配置时, 出现了配置不正确的问题, 后使用 @Configuration
注解解决
配置文件参考: https://github.com/spring-projects/spring-data-elasticsearch/tree/4.0.x
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.ElasticsearchConfigurationSupport;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Configuration
@EnableElasticsearchRepositories(basePackages="com.elastic.repository")
public class TransportClientConfig extends ElasticsearchConfigurationSupport {
@Bean
public Client elasticsearchClient() throws UnknownHostException {
Settings settings = Settings.builder().put("cluster.name", "docker-cluster").build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.1.125"), 9300));
return client;
}
@Bean(name = { "elasticsearchOperations", "elasticsearchTemplate" })
public ElasticsearchTemplate elasticsearchTemplate() throws UnknownHostException {
return new ElasticsearchTemplate(elasticsearchClient());
}
}
其他问题百度基本也说明了, 比如es配置文件中, 填写正确的cluster.name 和 修改host为0.0.0.0 之类的
端口号如果使用TransportClient需使用9300端口, 确保服务器9300端口正常访问