1. 程式人生 > >springboot2整合elasticsearch6.x(TransportClient方式)

springboot2整合elasticsearch6.x(TransportClient方式)

1.maven依賴

<elasticSearch.version>6.4.3</elasticSearch.version>

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>${elasticSearch.version}</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>${elasticSearch.version}</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>${elasticSearch.version}</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.plugin</groupId>
    <artifactId>transport-netty4-client</artifactId>
    <version>${elasticSearch.version}</version>
</dependency>

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-demo dev-es2分支