es工具类ElasticSearchClientHelper

package com.sohu.auto.db.es.core.es.client;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ElasticSearchClientHelper {
    private Map<String, Client> clientMap = new ConcurrentHashMap<>();

    private Map<String, Integer> ips = new HashMap<>(); // hostname port

    private String clusterName = "auto-es-pro";

    private boolean clientTransportSniff;

    public String getInetAddress() {
        return inetAddress;
    }

    public void setInetAddress(String inetAddress) {
        this.inetAddress = inetAddress;
    }

    private String inetAddress;

    public String getClusterName() {
        return clusterName;
    }

    public void setClusterName(String clusterName) {
        this.clusterName = clusterName;
    }

    public boolean isClientTransportSniff() {
        return clientTransportSniff;
    }

    public void setClientTransportSniff(boolean clientTransportSniff) {
        this.clientTransportSniff = clientTransportSniff;
    }

    private ElasticSearchClientHelper() {
        init();
    }
    public static final ElasticSearchClientHelper getInstance() {
        return ClientHolder.INSTANCE;
    }

    private static class ClientHolder {
        private static final ElasticSearchClientHelper INSTANCE = new ElasticSearchClientHelper();
    }

    private void init() {
        try {
            // 读取服务配置
            Configuration config = new PropertiesConfiguration("conf/es.properties");
            this.inetAddress = config.getString("es.transport.address");
            this.clientTransportSniff = config.getBoolean("es.client.transport.sniff");
            this.clusterName = config.getString("es.cluster.name");
            // 1.设定Settings
            // 设定集群名称
            Settings settings = Settings.builder().put("cluster.name", clusterName)
                    // 是否自动嗅探整个集群的状态,把集群中其他ES节点的ip添加到本地的客户端列表中
                    .put("client.transport.sniff", clientTransportSniff).build();
            // 2. 创建访问ES服务器的客户端
            TransportClient client = new PreBuiltTransportClient(settings);
            TransportAddress[] geTransportAddress = getAllAddress();
            if (geTransportAddress != null && geTransportAddress.length > 0) {
                for (int i = 0; i < geTransportAddress.length; i++) {
                    client.addTransportAddress(geTransportAddress[i]);
                }
            }
            clientMap.put(settings.get("cluster.name"),client);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private TransportAddress[] getAllAddress() throws UnknownHostException {
        if (inetAddress == null || inetAddress.length() <= 10) {
            return null;
        }
        String[] split = inetAddress.split(" ");
        List<TransportAddress> list = new ArrayList<>();

        for (String string : split) {
            if (StringUtils.isNotEmpty(string) && string.length() >= 10 && string.contains(":")) {
                String[] ip = string.split(":");
                if (ip.length == 2 && ip[0].matches("(\\d{1,3}\\.){3}\\d{1,3}") && ip[1].matches("\\d{1,6}")) {
                    list.add(new TransportAddress(InetAddress.getByName(ip[0]), Integer.valueOf(ip[1])));
                }
            }
        }
        TransportAddress[] addresses = new TransportAddress[list.size()];
        for (int i = 0; i < list.size(); i++) {
            addresses[i] = list.get(i);
        }
        return addresses;

    }


    public Client getClient() {
        return getClient(clusterName);
    }

    private Client getClient(String clusterName) {
        return clientMap.get(clusterName);
    }
}

 

Elasticsearch是一个开源的分布式搜索和分析引擎,它被广泛应用于全文搜索、日志分析、数据可视化等领域。Elasticsearch提供了丰富的API和功能,可以方便地进行数据索引、搜索、聚合和分析。 在使用Elasticsearch时,可以使用Java编写工具类来简化与Elasticsearch的交互。下面是一个简单的Elasticsearch工具类的示例: ```java import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; import java.io.IOException; public class ElasticsearchUtils { private RestHighLevelClient client; public ElasticsearchUtils() { client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); } public SearchResponse search(String index, String field, String keyword) throws IOException { SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery(field, keyword)); sourceBuilder.sort(field, SortOrder.DESC); SearchRequest searchRequest = new SearchRequest(index); searchRequest.source(sourceBuilder); return client.search(searchRequest, RequestOptions.DEFAULT); } public void close() throws IOException { client.close(); } } ``` 上述示例中的工具类使用了Elasticsearch的Java高级客户端(RestHighLevelClient)来与Elasticsearch进行交互。其中,`search`方法用于执行搜索操作,`close`方法用于关闭与Elasticsearch的连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值