RestHighLevelClient集成ES 7.X

Maven依赖

依赖版本号和elasticsearch版本号对应起来

		<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>elasticsearch-rest-client</artifactId>
			<version>7.17.6</version>
		</dependency>

		<!-- elasticSearch -->
		<dependency>
			<groupId>org.elasticsearch.client</groupId>
			<artifactId>elasticsearch-rest-high-level-client</artifactId>
			<version>7.17.6</version>
		</dependency>

		<dependency>
			<groupId>org.elasticsearch</groupId>
			<artifactId>elasticsearch</artifactId>
			<version>7.17.6</version>
			<scope>compile</scope>
		</dependency>

YML配置

spring:
  elasticsearch:
    rest:
      uris: http://127.0.0.1:9200,http://127.0.0.1:9201
      username: elastic
      password: ******

ElasticSearchConfig

集群带用户名密码


import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

@Configuration
public class ElasticSearchConfig {
    @Value("${spring.elasticsearch.rest.uris}")
    private String[] uris;

    @Value("${spring.elasticsearch.rest.username}")
    private String userName;

    @Value("${spring.elasticsearch.rest.password}")
    private String passWord;
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        HttpHost[] httpHosts = Arrays.stream(uris).map(HttpHost::create).toArray(HttpHost[]::new);
        RestClientBuilder builder = RestClient.builder(httpHosts);

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, passWord));
        builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
        return new RestHighLevelClient(builder);
}

集群无用户名密码


import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

@Configuration
public class ElasticSearchConfig {
    @Value("${spring.elasticsearch.rest.uris}")
    private String[] uris;
    @Bean
    public RestHighLevelClient restHighLevelClient() {
 	HttpHost[] httpHosts = Arrays.stream(uris).map(HttpHost::create).toArray(HttpHost[]::new);
 	RestClientBuilder builder = RestClient.builder(httpHosts);
		return new RestHighLevelClient(builder);
    }

}

实体类

@Data
public class CallingLog implements Serializable {

	private static final long serialVersionUID = 6211869625504817559L;


	private String id;

	private String index;
	private String type;
	
	private Date beginTime;
	private Date endTime;
	private String request;
	private String response;
	private String remark;
	private String callType;//调用类别
}

插入数据

import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.formula.functions.T;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;
@Component
public class EsClientUtils {

    private static final Logger logger = LoggerFactory.getLogger(EsClientUtils.class);

    /**
     * 默认超时时间
     */
    private long timeOut = 1L;

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    private Class<? extends T> tClass;

    /**
     * 单条数据插入
     *
     * @param t 放入的对象
     * @return 响应信息,放入es的基本信息(index、type、id)
     */
    public IndexResponse add(CallingLog t) throws NoSuchFieldException {
        if (checkIndexTypeId(t)) {
            return null;
        }
        // 按actv_log_230713 格式生成索引
        String indexStr = DateUtils.formatDate(new Date(), "yyMMdd");
        String index = t.getIndex();
        String type = "_doc";
        String id = IdUtils.fastUUID();
        final String jsonString = JSONObject.toJSONString(t);
        final IndexRequest request = new IndexRequest(t.getIndex() + indexStr, type, id)
                .source(jsonString, XContentType.JSON)
                .opType(DocWriteRequest.OpType.CREATE)
                .timeout(TimeValue.timeValueSeconds(timeOut));
        IndexResponse indexResponse = null;
        try {
            indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            logger.error("es(index:{},type:{},id:{})添加失败:", index, e);
        }
        return indexResponse;
    }

    /**
     * 检验必要的值
     *
     * @param t 与es存储对应的对象
     * @return true不符合,false符合
     */
    private boolean checkIndexTypeId(CallingLog t) {
        return t == null || t.getIndex() == null;
    }

}

使用实例

EsClientUtils esClientUtils = ApplicationContextHelper.getBean(EsClientUtils.class);
        CallingLog callingLog = new CallingLog();
        callingLog.setIndex("actv_test");
        callingLog.setCallName("3333");
        callingLog.setRequest("7777");
        callingLog.setRemark("6666");

        callingLog.setBeginTime(new Date());
        callingLog.setEndTime(new Date());
        callingLog.setResponse("2222");
        callingLog.setServiceNum("3333333");
        esClientUtils.add(crmCallingLog);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值