由于新版的ES逐渐放弃了对于Java TCP客户端的支持和维护,而是更推荐使用REST Client进行集群的操作,Springboot
项目可以使用starter
方便的集成使用,但是单纯的Spring项目并不能很优雅的直接使用RestHighLevelClient
进行操作,因此需要手动封装一个FactoryBean
进行集成。
1、封装Spring的FactoryBean
@Setter
@Slf4j
public class EsClientFactoryBean implements FactoryBean<RestHighLevelClient> {
/**
* ES鉴权header
*/
private static final String ES_AUTH_HEADER = "Authorization";
/**
* keep-alive时间默认30分钟
*/
private static final long KEEP_ALIVE_TIME = 1000 * 60 * 30;
/**
* 集群配置 host:port;host:port
*/
private String clusters;
/**
* ES鉴权用户名
*/
private String securityUser;
/**
* ES鉴权密码
*/
private String securityPassword;
/**
* 基础的base64生成
*
* @param username 用户名
* @param passwd 密码
*/
private static String basicAuthHeaderValue(String username, String passwd) {
CharBuffer chars = CharBuffer.allocate(username.length() + passwd.length() + 1);
byte[] charBytes = null;
try {
chars.put(username).