简体   繁体   中英

elasticsearch & java - InvocationTargetException and NoNodeAvailableException

I am trying to index an object to elasticsearch, but I am having no luck besides finding a lot of dead-ends...

My Application class looks like this:

import com.google.gson.Gson;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;

import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import static org.elasticsearch.common.xcontent.XContentFactory.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.elasticsearch.client.transport.TransportClient;

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private FilRepo repository;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9200));

//      repository.deleteAll();
        List<Fil> listFiler = new ArrayList();
        // save a couple of customers
//      repository.save(new Fil("Steffen-1", 5, new Date(), new Date()));
//      repository.save(new Fil("Steffen-2", 10, new Date(), new Date()));

        // fetch all customers
        System.out.println("Filer funder med findAll():");
        System.out.println("-------------------------------");

        for (Fil f : repository.findAll()) {
            listFiler.add(f);
            IndexResponse response = client.prepareIndex("elasticsearch", "fil")
                    .setSource(jsonBuilder()
                            .startObject()
                            .field("fil", f.filNavn)
                            .field("size", f.filStr)
                            .field("created", f.created)
                            .field("modified", f.modified)
                            .endObject()
                    )
                    .get();





                    System.out.println("RESPONSE ER HER: " + response.toString());
        }
        System.out.println(listFiler);
        System.out.println();

        // fetch an individual customer
        System.out.println("Customer found with findByFilNavn('Steffen-1'):");
        System.out.println("--------------------------------");
        System.out.println(repository.findByFilNavn("Steffen-1"));

        client.close();

    }
}

My elasticsearch is running which I have checked by going to localhost:9200 it looks like this:

name    "WpUHj5-"
cluster_name    "elasticsearch"
cluster_uuid    "nEgvRKklRveOr1ltZSPbeA"
version 
number  "5.5.0"
build_hash  "260387d"
build_date  "2017-06-30T23:16:05.735Z"
build_snapshot  false
lucene_version  "6.6.0"
tagline "You Know, for Search"

The error log I get from the mvn spring-boot:run is: 在此处输入图片说明

在此处输入图片说明

and the error on my Elasticsearch window: which basically says "an existing connection was closed by an external host"

在此处输入图片说明

First of all, it would be good to separate the configuration part from the business logic. So the configuration bean for elasticsearch should be following (note that the correct port for communication via TransportClient is 9300 , port 9200 is for REST, I think this is the main problem here but maybe not the only one):

@Configuration
public class ElasticsearchConfig {

    private static final Logger LOG = getLogger(ElasticsearchConfig.class); 

    private Client client;

    @SuppressWarnings("resource")
    @Bean
    public Client getClient() throws UnknownHostException {

        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .build();

        client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

        LOG.info("--ElasticSearch--");
        Map<String, String> asMap = client.settings().getAsMap();
        asMap.forEach((k, v) -> LOG.info(k + " = " + v));
        LOG.info("--ElasticSearch--");

        return client;      
    }

    @PreDestroy
    public void closeClient() {
        client.close();
    }

}

After initializing client object, for test purposes, you can check your logic (here the settings of client are printed) but it would be much much cleaner if you could move you logic to a separate service and work with client after injecting it with:

@Autowired
private Client client;

Main Spring Boot class:

@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "pl.jma.es.demo.esrepository")
public class EsDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(EsDemoApplication.class, args);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM