spring-es.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/elasticsearch
http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd">
<elasticsearch:transport-client id="client" cluster-nodes="es1:9300,es2:9300,es3:9300" cluster-name="test_es_cluster" />
<!-- 配置搜索模板 -->
<bean id="elasticsearchTemplate"
class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean>
</beans>
SpringBeanFactory获取bean
package com.leaf.elasticsearch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author ycc
*/
@Slf4j
public class SpringBeanFactory {
private transient static volatile SpringBeanFactory INSTANCE = null;
private ClassPathXmlApplicationContext context;
public static SpringBeanFactory getInstance(String... files) {
if (files.length == 0) {
files = new String[]{"classpath*:spring-*.xml"};
}
if (INSTANCE == null) {
synchronized (SpringBeanFactory.class) {
if (INSTANCE == null) {
INSTANCE = new SpringBeanFactory(files);
}
}
}
return INSTANCE;
}
private SpringBeanFactory(String... files) {
context = new ClassPathXmlApplicationContext(files);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
log.info("close SpringBeanFactory in shutdown hook");
context.close();
}
});
context.start();
}
public <T> T getBean(Class<T> clazz) {
return context.getBean(clazz);
}
}
测试类
package com.leaf.elasticsearch;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import java.util.List;
/**
* @created by ycc
* @since 2019-05-29
*/
public class TestEs {
public static void main(String[] args) {
ElasticsearchTemplate elasticsearchTemplate = SpringBeanFactory.getInstance().getBean(ElasticsearchTemplate.class);
NativeSearchQuery searchQuery = new NativeSearchQuery(QueryBuilders.matchAllQuery());
searchQuery.addIndices("skynet_social_twitter_status_2019_05");
searchQuery.addTypes("status");
searchQuery.setPageable(new PageRequest(1, 10));
UpdateQuery updateQuery = new UpdateQuery();
IndexQuery indexQuery = new IndexQuery();
long count = elasticsearchTemplate.count(searchQuery);
List<SocialStatus> socialStatusList = elasticsearchTemplate.queryForList(searchQuery, SocialStatus.class);
System.out.println(count);
}
}