ElasticSearch-Java单例模式获取TransportClient

1 Java中获取TransportClient的示例代码:

// 集群名称
String clusterName='';
String ip = '';
String port = '';
public static TransportClient getClient() {
        if (client == null) {

            Settings settings = Settings.builder().put("cluster.name", clusterName)
                    .put("client.transport.ignore_cluster_name", true)
                    .build();
            //同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建)
            synchronized (TransportClient.class) {
                if (client == null) {
                    client = new PreBuiltTransportClient(settings)
                            .addTransportAddress(new InetSocketTransportAddress(InetAddresses.forString(ip),
                                    Integer.parseInt(port)));
                }
            }
        }
        return client;
    }

2 SpringBoot项目启动后,首次获取TransportClient报java.lang.IllegalStateException: availableProcessors is already set to [8], rejecting [8]错误的解决办法

@SpringBootApplication
public class SpringBootTestElasticsearchApplication {

    public static void main(String[] args) {
        /**
         * Springboot整合Elasticsearch 在项目启动前设置一下的属性,防止报错
         * 解决netty冲突后初始化client时还会抛出异常
         * java.lang.IllegalStateException: availableProcessors is already set to [8], rejecting [8]
         */
        System.setProperty("es.set.netty.runtime.available.processors", "false");
        SpringApplication.run(SpringBootTestElasticsearchApplication.class, args);
    }
}

3 测试获取TransportClient

public static void main(String[]args) throws UnknownHostException {
                // 创建client
                TransportClient client = getClient();
                // 搜索数据
                SearchResponse response = client.prepareSearch("*").addSort("code_id.keyword", SortOrder.DESC).execute().actionGet();
                // 输出结果
                response.getHits().forEach(i->System.out.println(i.getScore()));
                // 关闭client
                client.close();
    }

你可能感兴趣的:(ElasticSearch)