转载于Spring Boot 集成Elastic Search 6.x
参考Spring Boot Elasticsearch
主要使用了 AbstractFactoryBean
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.2.4</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.2.4</version>
</dependency>
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchConfiguration extends AbstractFactoryBean {
private static final Logger LOG = LoggerFactory.getLogger(ElasticSearchConfiguration.class);
@Value("${elasticsearch.host}")
private String host;
private RestHighLevelClient restHighLevelClient;
@Override
public void destroy() throws Exception {
// 关闭Client
if (restHighLevelClient != null) {
restHighLevelClient.close();
}
}
@Override
public Class<RestHighLevelClient> getObjectType() {
return RestHighLevelClient.class;
}
@Override
public boolean isSingleton() {
return false;
}
@Override
protected Object createInstance() throws Exception {
try {
// 如果有多个节点,构建多个HttpHost
restHighLevelClient = new RestHighLevelClient(
RestClient.builder(
new HttpHost(host, 9200, "http")));
} catch (Exception e) {
LOG.error(e.getMessage());
}
return restHighLevelClient;
}
}
然后在service中需要用到的地方
@Autowired
private RestHighLevelClient restHighLevelClient;
日志记录
compile('org.slf4j:slf4j-api:1.7.14')
compile('org.apache.logging.log4j:log4j-api:2.11.1')
compile('org.apache.logging.log4j:log4j-core:2.11.1')
compile('org.apache.logging.log4j:log4j-to-slf4j:2.11.1')
否则会提示ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
。另外,是不用写log4j2.xml文件的。
网友评论