当前位置: 首页 > article >正文

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);

http://www.kler.cn/a/37177.html

相关文章:

  • Vue-Router(4) 学习之动态路由二
  • 与君共勉之!
  • 用ChatGPT解析Wireshark抓取的数据包样例
  • Java+Vue+Uniapp全端WMS仓库管理系统
  • 机器学习——决策树1(三种算法)
  • JS--es6模板字符串
  • ModaHub魔搭社区:AI原生云向量数据库Zilliz Cloud与 LangChain 集成搭建智能文档问答系统
  • elementUI 表格页面层级嵌套过多不及时刷新/错位的解决办法
  • 一文了解Docker之网络模型
  • 什么是用电信息采集系统?
  • C# SQL代码字符拼接
  • DaVinci Resolve Studio 18对Mac和Windows系统的要求
  • NB-IoT模块(BC系列—BC95)详解
  • 《大大简化每次运行bochs的命令行》ubuntu里安装vscode + makefile文件基本编写 + shell命令
  • Nginx 常用的安全屏蔽规则
  • 服务保护 Sentinel
  • Nacos(服务注册与发现)+SpringBoot+openFeign项目集成
  • 玩转ChatGPT:Code interpreter (vol. 1)
  • 7.12~7.13学习总结
  • 性能测试 jmeter 的 beanshell 脚本的 2 个常用例子