springboot2 통합 elasticsearch6.x(TransportClient 방식)

4025 단어 javaweb
1.maven 의존
6.4.3


    org.elasticsearch
    elasticsearch
    ${elasticSearch.version}


    org.elasticsearch.client
    transport
    ${elasticSearch.version}


    org.elasticsearch.client
    elasticsearch-rest-high-level-client
    ${elasticSearch.version}


    org.elasticsearch.plugin
    transport-netty4-client
    ${elasticSearch.version}


2.es.properties
elasticsearch.cluster-name=elasticsearch
#  , 
elasticsearch.cluster-nodes=172.22.2.133:9300

3.ESConfig
@Configuration
@PropertySources(value = {@PropertySource("classpath:es.properties")})
public class ESConfig {
    private static final Logger LOGGER  = LoggerFactory.getLogger(ESConfig.class);
    private static final String CLUSTER_NODES_SPLIT_SYMBOL = ",";
    private static final String HOST_PORT_SPLIT_SYMBOL = ":";

    @Autowired
    private Environment environment;

    @Bean
    public TransportClient getTransportClient() {
        LOGGER.info("elasticsearch init.");
        String clusterName = environment.getRequiredProperty("elasticsearch.cluster-name");
        if (StringUtils.isEmpty(clusterName)) {
            throw new RuntimeException("elasticsearch.cluster-name is empty.");
        }
        String clusterNodes = environment.getRequiredProperty("elasticsearch.cluster-nodes");
        if (StringUtils.isEmpty(clusterNodes)) {
            throw new RuntimeException("elasticsearch.cluster-nodes is empty.");
        }
        try {
            Settings settings = Settings.builder().put("cluster.name", clusterName.trim())
                    .put("client.transport.sniff", true).build();
            TransportClient transportClient = new PreBuiltTransportClient(settings);
            String[] clusterNodeArray = clusterNodes.trim().split(CLUSTER_NODES_SPLIT_SYMBOL);
            for (String clusterNode : clusterNodeArray) {
                String[] clusterNodeInfoArray = clusterNode.trim().split(HOST_PORT_SPLIT_SYMBOL);
                TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(clusterNodeInfoArray[0]),
                        Integer.parseInt(clusterNodeInfoArray[1]));
                transportClient.addTransportAddress(transportAddress);
            }
            LOGGER.info("elasticsearch init success.");
            return transportClient;
        } catch (Exception e) {
            throw new RuntimeException("elasticsearch init fail.");
        }
    }
}

4. 테스트
public class ESConstant {
    public static final String DATA_INDEX_NAME = "data";
    public static final String DATA_INDEX_TYPE = "user";
}

@RunWith(SpringRunner.class)
@SpringBootTest
public class SingleDocTests {
    @Autowired
    private TransportClient transportClient;

    @Test
    public void addTest() throws Exception {
        String id = "10000";
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject()
                .field("name", "test001")
                .field("age", 501)
                .field("address", " ")
                .endObject();
        IndexResponse indexResponse = transportClient.prepareIndex(ESConstant.DATA_INDEX_NAME,
                ESConstant.DATA_INDEX_TYPE, id).setSource(xContentBuilder).execute().get();
        //  (CREATED)  (OK)
        System.out.println(indexResponse.status());
    }
}

소스 코드:https://gitee.com/jsjack_wang/springboot-demodev-es2 분기

좋은 웹페이지 즐겨찾기