elasticsearch使用环境简洁参考上篇:
1.引用elasticsearch的操作客户单jar
pom如下:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.5.0</version>
</dependency>
如果项目中使用了x-pack-transport应用对应版本的jar
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>x-pack-transport</artifactId>
<version>5.5.0</version>
</dependency>
2.创建查询的bean对象,参数放在配置文件中。
#es配置
es.clusterName=es_test
es.xpackSecurityUser=elastic:password
es.inetAddress=10.1.1.1:9300,10.1.1.2:9300,10.1.1.2:9300
clusterName在elasticsearch安装完成后,默认访问IP:9200可查看这参数
xpackSecurityUser是使用x-pack-transport,es需要用户名和密码登录,做的一层安全机制,如果未使用则为空即可
inetAddress是es的IP地址和端口,默认client端口为9300.此处是支持es集群,多个IP使用 "," 分割即可。
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import com.whty.framework.base.util.StringUtil;
/**
* 使用javaConfig方式配置
* @version 1.0.0
* @date 2018 -11-09
*/
@Component
@Configuration
public class EsConfig {
private static final int DEFAULT_PORT = 9300;
@Value(value = "${es.clusterName}")
String clusterName;
@Value(value = "${es.xpackSecurityUser}")
String xpackSecurityUser;
@Value(value = "${es.inetAddress}")
String inetAddress;
@Bean
public TransportClient transportClient() throws UnknownHostException {
Settings.Builder builder = Settings.builder().put("cluster.name", clusterName);
TransportClient client = null;
if (StringUtil.isNotBlank(xpackSecurityUser)) {
builder.put("xpack.security.user", xpackSecurityUser);
client = new PreBuiltXPackTransportClient(builder.build());
} else {
client = new PreBuiltTransportClient(builder.build());
}
String[] hostNames = inetAddress.split(",");
for (String hostName : hostNames) {
String[] hostPort = hostName.trim().split(":");
String host = hostPort[0].trim();
int port = hostPort.length == 2 ? Integer.parseInt(hostPort[1].trim()) : DEFAULT_PORT;
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
}
return client;
}
}
到此时client 构建完成。
如果在其他地方需要使用使用bean对象调用对应的api方法
@Autowired
private TransportClient client;