最后,我使用了普通的 Elasticseach java 客户端。下面的代码可能有用。
<bean id="esConnection" class="com.es.connection.ESConnection" scope="singleton" autowire="byName">
<property name="host" value="${es.host}" />
<property name="port" value="${es.port}" />
<property name="clusterName" value="${es.cluster}" />
</bean>
import javax.annotation.PostConstruct;
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;
public class ESConnection {
TransportClient client;
private String host;
private int port;
private String clusterName;
public ESConnection() {
}
public ESConnection(String host,int port,String clusterName) {
this.host = host;
this.clusterName = clusterName;
this.port = port;
}
@PostConstruct
public void connect() {
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name",clusterName)
.build();
client = new TransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(host,port));
}
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public Client getClient() {
return (Client) client;
}
public void close() {
if (client != null) {
client.close();
}
}
@Override
public String toString() {
return String.format("%s, Host: %s, Port: %s, Cluster: %s", super.toString(), host, port, clusterName);
}
}
在启动监听器中,
public class StartupListener implements ServletContextListener {
@Autowired
ESConnection esConnection;
public void contextInitialized(ServletContextEvent sce) {
try {
ServletContext context = sce.getServletContext();
context.setAttribute("esConnection", esConnection);
} catch (SchedulerException se) {
} catch (Exception e) {
}
}
public void contextDestroyed(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
if (this.esConnection != null) {
this.esConnection.close();
context.removeAttribute("esConnection");
}
}
}