如何在Spring中注入ElasticSearch实例
1个回答
展开全部
package cn.bizbook.product.elk.config;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by qindongliang on 2016/4/6.
*/
@Configuration
public class FactoryBean {
//配置文件工具类
@Autowired
private ESConf esConf;
//注入的ElasticSearch实例
@Bean(name = "client")
public Client getESClient(){
//设置集群名字
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", esConf.getClusterName())
.build();
Client client=new TransportClient(settings);
//读取的ip列表是以逗号分隔的
for(String ip:esConf.getIps().split(",")){
((TransportClient)client).addTransportAddress(new InetSocketTransportAddress(ip,esConf.getPort()));
}
return client;
}
}
最后来看下,如何在DAO层,引用client实例,非常easy:
Java代码
@Resource(name = "client")
private Client client;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by qindongliang on 2016/4/6.
*/
@Configuration
public class FactoryBean {
//配置文件工具类
@Autowired
private ESConf esConf;
//注入的ElasticSearch实例
@Bean(name = "client")
public Client getESClient(){
//设置集群名字
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", esConf.getClusterName())
.build();
Client client=new TransportClient(settings);
//读取的ip列表是以逗号分隔的
for(String ip:esConf.getIps().split(",")){
((TransportClient)client).addTransportAddress(new InetSocketTransportAddress(ip,esConf.getPort()));
}
return client;
}
}
最后来看下,如何在DAO层,引用client实例,非常easy:
Java代码
@Resource(name = "client")
private Client client;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询