美文网首页
ES Low Level REST Client With Au

ES Low Level REST Client With Au

作者: 程序员小白成长记 | 来源:发表于2020-11-09 17:47 被阅读0次

前言:
公司ES集群由ES5.5升级到了ES7.4,而且加了用户认证,本文记录下涉及的相关的内容

目录
一、相关代码
—— 1.1 application.properties 配置文件
—— 1.2 EsConfig 配置类
—— 1.3 EsService service
——1.4 EsController controller
二、参考

一、相关代码

1.1 application.properties

es.schema=http
es.address=ip:port
es.userName=user
es.password=password
es.connectTimeout=5000
es.socketTimeout=5000
es.connectionRequestTimeout=5000
es.maxConnectNum=100
es.maxConnectPerRoute= 100

1.2 EsConfig

import org.apache.commons.lang3.StringUtils;
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.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Objects;

@Configuration
@ConfigurationProperties(prefix = "es")
public class EsConfig {

    /**
     * 协议
     */
    private String schema;

    /**
     * 集群地址、端口号
     */
    private String[] address;

    /**
     * 用户名
     */
    private String userName;

    /**
     * 密码
     */
    private String password;

    /**
     * 连接超时时间
     */
    private int connectTimeout;

    /**
     * Socket 连接超时时间
     */
    private int socketTimeout;

    /**
     * 获取连接的超时时间
     */
    private int connectionRequestTimeout;

    /**
     * 最大连接数
     */
    private int maxConnectNum;

    /**
     * 最大路由连接数
     */
    private int maxConnectPerRoute;

    public String getSchema() {
        return schema;
    }

    public void setSchema(String schema) {
        this.schema = schema;
    }

    public String[] getAddress() {
        return address;
    }

    public void setAddress(String[] address) {
        this.address = address;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public int getSocketTimeout() {
        return socketTimeout;
    }

    public void setSocketTimeout(int socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    public int getConnectionRequestTimeout() {
        return connectionRequestTimeout;
    }

    public void setConnectionRequestTimeout(int connectionRequestTimeout) {
        this.connectionRequestTimeout = connectionRequestTimeout;
    }

    public int getMaxConnectNum() {
        return maxConnectNum;
    }

    public void setMaxConnectNum(int maxConnectNum) {
        this.maxConnectNum = maxConnectNum;
    }

    public int getMaxConnectPerRoute() {
        return maxConnectPerRoute;
    }

    public void setMaxConnectPerRoute(int maxConnectPerRoute) {
        this.maxConnectPerRoute = maxConnectPerRoute;
    }

    /**
     * ES Low Level Client
     *
     * @return
     */
    @Bean
    public RestClient getEsClient() {

        HttpHost[] hosts = Arrays.stream(address)
                .map(this::makeHttpHost)
                .filter(Objects::nonNull)
                .toArray(HttpHost[]::new);


        final CredentialsProvider credentialsProvider =
                new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));

        RestClientBuilder builder = RestClient.builder(hosts)
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(
                            HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder
                                .setDefaultCredentialsProvider(credentialsProvider);
                    }
                });
        return builder.build();
    }

    private HttpHost makeHttpHost(String s) {
        assert StringUtils.isNotEmpty(s);
        String[] address = s.split(":");
        if (address.length == 2) {
            String ip = address[0];
            int port = Integer.parseInt(address[1]);
            return new HttpHost(ip, port, schema);
        } else {
            return null;
        }
    }
}

1.3 EsService

@Service
public class EsService {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestClient restClient;

    public EsService() {
    }

    public String getIndex(){
        String endpoint = EsConstants.SLASH + EsConstants.INDEXNAME;
        Map<String, String> queryParams = new HashMap<>();
        queryParams.put(EsConstants.QUERYPARAM_PRETTY, null);
        String response = executeRequest(HttpEsEnum.GET.toString(), endpoint,null, queryParams);
        logger.debug("==== response: {}", response);
        return response;
    }


    /**
     * ES执行Rest请求
     *
     * @param method
     * @param endpoint
     * @param requestBody
     * @param queryParams
     * @return
     */
    public String executeRequest(String method, String endpoint, String requestBody, Map<String, String> queryParams) {
        if (queryParams == null) {
            queryParams = Collections.emptyMap();
        }
        HttpEntity entity = null;
        if (StringUtils.isNotEmpty(requestBody)) {
            entity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON);
        }

        String responseBody = null;
        try {
            logger.debug("execCmd, method={}, endpoint={}, params={}, entity={}", method, endpoint, queryParams, entity);
            Response response = restClient.performRequest(method, endpoint, queryParams, entity);
            logger.debug("Response statusCode = {}", response.getStatusLine().getStatusCode());
            responseBody = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            logger.error("Exec es cmd error. ", e);
        }
        return responseBody;
    }
}

1.4 EsController

@RestController
@RequestMapping("/api/v1/es")
public class EsController {

    @Autowired
    private EsService esService;

    @ResponseBody
    @RequestMapping(value = "/getIndex", method = RequestMethod.GET)
    public String getIndex() {
        return esService.getIndex();
    }
}

二、参考

【1】使用RestHighLevelClient 连接带有用户名密码ES机器
【2】ElasticSearch-Java-low-level-rest-client官方文档翻译
【3】【es笔记三】Java Low Level REST Client

相关文章

网友评论

      本文标题:ES Low Level REST Client With Au

      本文链接:https://www.haomeiwen.com/subject/xecavktx.html