JAVA 连接ElasticSearch不成功,帮忙看下 谢谢

时间:2022-09-13 00:09:58
 public static void main(String[] args) {
        Client client = null;
        Settings settings = Settings.settingsBuilder()
                .put("client.transport.sniff", true)
                .put("cluster.name", "elasticsearch").build();
        try {
            client = TransportClient.builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9200));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        SearchRequestBuilder sbuilder = client.prepareSearch("megacorp") //index name
                .setTypes("employee") //type name
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.termQuery("first_name", "Douglas"))      // Query
                .setPostFilter(QueryBuilders.rangeQuery("age").from(20).to(40))  // Filter
                .setFrom(0).setSize(60).setExplain(true);
        System.out.println(sbuilder.toString());
        SearchResponse response = sbuilder.execute().actionGet();
        System.out.println(response.toString());
    }



错误信息:
Disconnected from the target VM, address: '127.0.0.1:6666', transport: 'socket'
Exception in thread "main" java.lang.VerifyError: (class: org/jboss/netty/channel/socket/nio/NioWorkerPool, method: newWorker signature: (Ljava/util/concurrent/Executor;)Lorg/jboss/netty/channel/socket/nio/AbstractNioWorker;) Wrong return type in function
at org.elasticsearch.transport.netty.NettyTransport.createClientBootstrap(NettyTransport.java:344)
at org.elasticsearch.transport.netty.NettyTransport.doStart(NettyTransport.java:279)
at org.elasticsearch.common.component.AbstractLifecycleComponent.start(AbstractLifecycleComponent.java:68)
at org.elasticsearch.transport.TransportService.doStart(TransportService.java:182)
at org.elasticsearch.common.component.AbstractLifecycleComponent.start(AbstractLifecycleComponent.java:68)
at org.elasticsearch.client.transport.TransportClient$Builder.build(TransportClient.java:162)
at com.lvmama.cobra.job.ESRequest.main(ESRequest.java:26)

10 个解决方案

#1


遇到同样的问题,你解决了吗?

#2


端口用9300

#3


集群名称默认为elasticsearch,没有修改过无需setting可以建立连接:
Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("", 9300));
如果修改过集群的名称:
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", "elasticsearch_01").build();
Client client = new TransportClient(settings)       
.addTransportAddress(new InetSocketTransportAddress("", 9300));

#4


楼主解决了嘛

#5


2楼说的对   端口用9300   搭建集群的时候三台服务器也都是9300 

#6



 public static void main(String[] args) {
        // on startup
        Client client;
        try {
            client = new TransportClient()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.0.94"), 9300));

            IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
                    .setSource(jsonBuilder()
                            .startObject()
                            .field("user", "kimchy")
                            .field("postDate", new Date())
                            .field("message", "trying out Elasticsearch")
                            .endObject()
                    )
                    .get();

            System.out.println(response);
            // on shutdown
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public TransportClient getInstance() {
        if (instance == null) {
            int port = DEFAULT_PORT;
            if (StringUtils.isNotBlank(esPort)) {
                port = Integer.parseInt(esPort);
            }
            if (StringUtils.isNotEmpty(esHost) && StringUtils.isNotEmpty(clusterName)) {
                String[] esNoses = esHost.split(",");
                try {
                    Settings settings = ImmutableSettings.settingsBuilder()
                            .put("client.transport.sniff", true)
                            .put("cluster.name", clusterName).build();

                    instance = new TransportClient(settings);
                    for (String ips : esNoses) {
                        instance.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ips), port));
                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else {
                System.out.println("server/host 不能为空");
            }
        }
        return instance;
    }
public void addSingle(ApiInvokeInfo apiInvokeInfo) {
        try {
            XContentBuilder jsonObject = XContentFactory.jsonBuilder().startObject();

            jsonObject.field("threadno", apiInvokeInfo.getThreadNo())
                    .field("methodname", apiInvokeInfo.getMethodName())
                    .field("version", apiInvokeInfo.getVersion())
                    .field("firstchannel", apiInvokeInfo.getFirstChannel())
                    .field("latitude", apiInvokeInfo.getLatitude())
                    .field("longtitude", apiInvokeInfo.getLongtitude())
                    .field("location", apiInvokeInfo.getLocation())
                    .field("appversion", apiInvokeInfo.getAppVersion())
                    .field("udid", apiInvokeInfo.getUdid())
                    .field("ip", apiInvokeInfo.getIp())
                    .field("userid", apiInvokeInfo.getUserId())
                    .field("invoketime", apiInvokeInfo.getInvokeTime())
                    .field("issuccess", apiInvokeInfo.getIsSuccess())
                    .field("costtime", apiInvokeInfo.getCostTime())
                    .field("debuginfo", apiInvokeInfo.getDebugInfo())
                    .field("isaccess", apiInvokeInfo.getAccess())
                    .endObject();

            IndexRequest indexRequest = new IndexRequest();
            IndexResponse indexResponse =
                    getInstance().index(indexRequest.index(esClient.getSuitableIndice()).type(esClient.getQueryType()).source(jsonObject)).actionGet();

            if (!indexResponse.isCreated()) {
                System.out.println("发送消息失败 ES");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

#7



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring-test.xml")
public class ESTests {

    private static volatile TransportClient instance = null;

    @Value("${es.host}")
    private String esHost;

    @Value("${es.clusterName}")
    private String clusterName;

    @Value("${es.port}")
    private String esPort;

    @Value("${es.indices}")
    private String indices;

    @Value("${es.apimethod.queryType}")
    private String queryType;

    @Autowired
    ApiMethodService apiMethodService;

    @Autowired
    ESSearchHelper esSearchHelper;

    @Autowired
    ESClient esClient;

    private static final int DEFAULT_PORT = 9300;

    public static void main(String[] args) {

#8


netty包冲突了

#9


楼上一语道破天机,确实是netty冲突了,我解决如下,修改pom (不知道会不会带来其它问题)
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dubbo</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring</artifactId>
        </exclusion>
        <exclusion>
            <artifactId>netty</artifactId>
            <groupId>org.jboss.netty</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>netty</artifactId>
            <groupId>io.netty</groupId>
        </exclusion>
    </exclusions>
</dependency>

#10


8楼正解8楼正解8楼正解8楼正解

#1


遇到同样的问题,你解决了吗?

#2


端口用9300

#3


集群名称默认为elasticsearch,没有修改过无需setting可以建立连接:
Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("", 9300));
如果修改过集群的名称:
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", "elasticsearch_01").build();
Client client = new TransportClient(settings)       
.addTransportAddress(new InetSocketTransportAddress("", 9300));

#4


楼主解决了嘛

#5


2楼说的对   端口用9300   搭建集群的时候三台服务器也都是9300 

#6



 public static void main(String[] args) {
        // on startup
        Client client;
        try {
            client = new TransportClient()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.0.94"), 9300));

            IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
                    .setSource(jsonBuilder()
                            .startObject()
                            .field("user", "kimchy")
                            .field("postDate", new Date())
                            .field("message", "trying out Elasticsearch")
                            .endObject()
                    )
                    .get();

            System.out.println(response);
            // on shutdown
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public TransportClient getInstance() {
        if (instance == null) {
            int port = DEFAULT_PORT;
            if (StringUtils.isNotBlank(esPort)) {
                port = Integer.parseInt(esPort);
            }
            if (StringUtils.isNotEmpty(esHost) && StringUtils.isNotEmpty(clusterName)) {
                String[] esNoses = esHost.split(",");
                try {
                    Settings settings = ImmutableSettings.settingsBuilder()
                            .put("client.transport.sniff", true)
                            .put("cluster.name", clusterName).build();

                    instance = new TransportClient(settings);
                    for (String ips : esNoses) {
                        instance.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ips), port));
                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else {
                System.out.println("server/host 不能为空");
            }
        }
        return instance;
    }
public void addSingle(ApiInvokeInfo apiInvokeInfo) {
        try {
            XContentBuilder jsonObject = XContentFactory.jsonBuilder().startObject();

            jsonObject.field("threadno", apiInvokeInfo.getThreadNo())
                    .field("methodname", apiInvokeInfo.getMethodName())
                    .field("version", apiInvokeInfo.getVersion())
                    .field("firstchannel", apiInvokeInfo.getFirstChannel())
                    .field("latitude", apiInvokeInfo.getLatitude())
                    .field("longtitude", apiInvokeInfo.getLongtitude())
                    .field("location", apiInvokeInfo.getLocation())
                    .field("appversion", apiInvokeInfo.getAppVersion())
                    .field("udid", apiInvokeInfo.getUdid())
                    .field("ip", apiInvokeInfo.getIp())
                    .field("userid", apiInvokeInfo.getUserId())
                    .field("invoketime", apiInvokeInfo.getInvokeTime())
                    .field("issuccess", apiInvokeInfo.getIsSuccess())
                    .field("costtime", apiInvokeInfo.getCostTime())
                    .field("debuginfo", apiInvokeInfo.getDebugInfo())
                    .field("isaccess", apiInvokeInfo.getAccess())
                    .endObject();

            IndexRequest indexRequest = new IndexRequest();
            IndexResponse indexResponse =
                    getInstance().index(indexRequest.index(esClient.getSuitableIndice()).type(esClient.getQueryType()).source(jsonObject)).actionGet();

            if (!indexResponse.isCreated()) {
                System.out.println("发送消息失败 ES");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

#7



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring-test.xml")
public class ESTests {

    private static volatile TransportClient instance = null;

    @Value("${es.host}")
    private String esHost;

    @Value("${es.clusterName}")
    private String clusterName;

    @Value("${es.port}")
    private String esPort;

    @Value("${es.indices}")
    private String indices;

    @Value("${es.apimethod.queryType}")
    private String queryType;

    @Autowired
    ApiMethodService apiMethodService;

    @Autowired
    ESSearchHelper esSearchHelper;

    @Autowired
    ESClient esClient;

    private static final int DEFAULT_PORT = 9300;

    public static void main(String[] args) {

#8


netty包冲突了

#9


楼上一语道破天机,确实是netty冲突了,我解决如下,修改pom (不知道会不会带来其它问题)
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dubbo</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework</groupId>
            <artifactId>spring</artifactId>
        </exclusion>
        <exclusion>
            <artifactId>netty</artifactId>
            <groupId>org.jboss.netty</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>netty</artifactId>
            <groupId>io.netty</groupId>
        </exclusion>
    </exclusions>
</dependency>

#10


8楼正解8楼正解8楼正解8楼正解