转载

在Spring Boot 2.0中使用ElasticSearch

演示的目标

  • 使用 Spring Data ElasticSearch 连接并查询嵌入式ElasticSearch节点
  • 使用 Spring Data ElasticSearch 连接并查询外部ElasticSearch节点
  • 所有在ElasticSearch API 5.5.0中运行的东西都嵌入在Spring Boot 2.0中

演示先决条件:

我们要将以下文档保存到ElasticSearch中:

@Document(indexName = "dataexchangecode", type = "dataTransferCode")
public class DataTransfer {

    @Id
    private String id;

    private String dataExchangeCode;

    private String data;

    public DataTransfer() {
    }

    /**
     * @param id
     * @param dataExchangeCode
     * @param data
     */<font>
    <b>public</b> DataTransfer(<b>final</b> String id, <b>final</b> String dataExchangeCode, <b>final</b> String data) {
        <b>this</b>.id = id;
        <b>this</b>.dataExchangeCode = dataExchangeCode;
        <b>this</b>.data = data;
    }

    <b>public</b> String getId() {
        <b>return</b> id;
    }

    <b>public</b> <b>void</b> setId(String id) {
        <b>this</b>.id = id;
    }

    <b>public</b> String getDataExchangeCode() {
        <b>return</b> dataExchangeCode;
    }

    <b>public</b> <b>void</b> setDataExchangeCode(String dataExchangeCode) {
        <b>this</b>.dataExchangeCode = dataExchangeCode;
    }

    <b>public</b> String getData() {
        <b>return</b> data;
    }

    <b>public</b> <b>void</b> setData(String data) {
        <b>this</b>.data = data;
    }

    @Override
    <b>public</b> String toString() {
        <b>return</b> <b>this</b>.id+
           <b>this</b>.dataExchangeCode+
           <b>this</b>.id;
    }
}
</font>

要了解indexName 和参数类型,可检查 document . 

为了测试目的,让我们创建以下两个REST控制器来调用Spring Data ElasticSearch CRUD存储库:

@Component
@RestController
<b>public</b> <b>class</b> HomeController {

    @Autowired
    <b>private</b> DataTransferRepository dataTransferRepository;

    @GetMapping(value = <font>"/prepareData"</font><font>)
    <b>public</b> String prepareESData() {
        <b>final</b> DataTransfer data = <b>new</b> DataTransfer(</font><font>"1"</font><font>, </font><font>"AW_INPUT"</font><font>, </font><font>"<XML>"</font><font>);
        dataTransferRepository.save(data);

        <b>final</b> DataTransfer data2 = <b>new</b> DataTransfer(</font><font>"2"</font><font>, </font><font>"BSL_INPUT"</font><font>, </font><font>"<XML>"</font><font>);
        dataTransferRepository.save(data2);

        <b>return</b> </font><font>"Data saved into elastic search!"</font><font>;
    }

    @GetMapping(value = </font><font>"/get/{id}"</font><font>)
    <b>public</b> DataTransfer getDataTransfer(@PathVariable(</font><font>"id"</font><font>) String id) {
        <b>return</b> dataTransferRepository.findById(id).get();
    }
}
</font>

连接并查询嵌入式ElasticSearch节点

构建本地节点时请记住,ElasticSearch API 5.x已针对指定用于构建本地ES节点的NodeBuilder类进行了更改。例如,检查 此 stackoverflow讨论。ES文档说明:

NodeBuilder已被删除。虽然直接在应用程序中使用Node不受官方支持,
但它仍然可以使用Node(Settings)构造函数构建。

下面是我所做的:

@Profile(<font>"localNode"</font><font>)
@Bean
<b>public</b> Node createLocalNode() throws NodeValidationException {
    <b>final</b> String tmpDir = System.getProperty(</font><font>"java.io.tmpdir"</font><font>);
    Settings.Builder elasticsearchSettings =
            Settings.builder()
                    .put(</font><font>"cluster.name"</font><font>, EsClusterName)
                    .put(</font><font>"path.data"</font><font>, <b>new</b> File(tmpDir, </font><font>"data"</font><font>).getAbsolutePath())
                    .put(</font><font>"path.logs"</font><font>, <b>new</b> File(tmpDir, </font><font>"logs"</font><font>).getAbsolutePath())
                    .put(</font><font>"transport.type"</font><font>,</font><font>"local"</font><font>)
                    .put(</font><font>"http.enabled"</font><font>,</font><font>"false"</font><font>)
                    .put(</font><font>"path.home"</font><font>, tmpDir);

    <b>final</b> Node node = <b>new</b> Node(elasticsearchSettings.build());
    node.start();

    <b>return</b> node;
}
</font>

有关节点参数列表,请查看 以下 文档。要使Spring Data ElasticSearch存储库正常工作,我们需要ElasticsearchTemplate:

@Profile(<font>"localNode"</font><font>)
@Bean(name=</font><font>"elasticsearchTemplate"</font><font>)
<b>public</b> ElasticsearchTemplate elasticsearchTemplate2() throws Exception {
    <b>return</b> <b>new</b> ElasticsearchTemplate(createLocalNode().client());
}
</font>

这将根据您的需要使用 NodeClient 启动ElasticsearchTemplate 。Definitelly要注意以下两件事:

  • NodeClient和TransportClient 之间的 区别
  • 最重要的 是,不推荐使用TransportClient

测试本地ElasticSearch节点

首先,我们需要构建项目:

$ mvn clean install

然后使用localNode spring profile运行Spring Boot 2.0应用程序:

$ java -jar -Dspring.profiles.active=localNode target/demo-0.0.1-SNAPSHOT.jar

ES本地节点应该启动了。

现在让我们测试一下,首先调用REST控制器端点将数据加载到ElasticSearch中:

curl http:<font><i>//localhost:8080/prepareData</i></font><font>
Data saved into elastic search!
</font>

然后我们可以查询数据:

$ curl http:<font><i>//localhost:8080/get/1 {"id":"1","dataExchangeCode":"AW_INPUT","data":"<XML>"}</i></font><font>
</font>
$ curl http:<font><i>//localhost:8080/get/2 {"id":"2","dataExchangeCode":"BSL_INPUT","data":"<XML>"}</i></font><font>
</font>

好的,本地嵌入式节点工作正常!

连接并查询外部ElasticSearch节点

在这种情况下,我们不需要嵌入任何本地ES节点,我们只需要启动ES客户端。以下配置互联网:

Settings settings = Settings.builder()
                      .put(<font>"cluster.name"</font><font>, EsClusterName).build();
     TransportClient client = <b>new</b> PreBuiltTransportClient(settings);
     client.addTransportAddress(
            <b>new</b> InetSocketTransportAddress(
                    InetAddress.getByName(EsHost), EsPort));
</font>

好吧,嵌入在Spring Boot 2.0中的ES API不能与PreBuiltTransportClient一起使用,因为它需要Netty3Plugin,这个无法放到maven依赖项中。如果您仍然不希望 highlevel REST API ,可以还是使用TransportClientFactoryBean 委托给SpringDataTransportClient

@Profile(<font>"!localNode"</font><font>)
@Bean
<b>public</b> Client client() throws Exception {
    </font><font><i>/**
     * PreBuiltTransportClient works fine, but requires Netty3Plugin
     * and Spring Boot offers only Netty4Plugin. Needs extra dependencies.

     Settings settings = Settings.builder()
                      .put("cluster.name", EsClusterName).build();
     TransportClient client = new PreBuiltTransportClient(settings);
     client.addTransportAddress(
            new InetSocketTransportAddress(
                    InetAddress.getByName(EsHost), EsPort));
     return client;
     */</i></font><font>

    TransportClientFactoryBean client = <b>new</b> TransportClientFactoryBean();
    client.setClusterName(EsClusterName);

    client.afterPropertiesSet();

    <b>return</b> client.getObject();
}
</font>

当然,我们需要再次使用ElasticsearchTemplate来使Spring Data ES工作:

@Profile(<font>"!localNode"</font><font>)
@Bean(name = </font><font>"elasticsearchTemplate"</font><font>)
<b>public</b> ElasticsearchOperations elasticsearchTemplate1() throws Exception {
    <b>return</b> <b>new</b> ElasticsearchTemplate(client());
}
</font>

准备好代码,让我们测试整个场景:

打开终端并启动外部ES服务器

$ elasticsearch

验证外部elasticsearch服务器是否正在运行:

$ curl http:<font><i>//localhost:9200 </i></font><font>
{
  </font><font>"name"</font><font> : </font><font>"NmF778a"</font><font>,
  </font><font>"cluster_name"</font><font> : </font><font>"elasticsearch_tomask79"</font><font>,
  </font><font>"cluster_uuid"</font><font> : </font><font>"Z0CfKNMxSNGqfkUONZ6bRg"</font><font>,
  </font><font>"version"</font><font> : {
    </font><font>"number"</font><font> : </font><font>"6.4.2"</font><font>,
    </font><font>"build_flavor"</font><font> : </font><font>"oss"</font><font>,
    </font><font>"build_type"</font><font> : </font><font>"tar"</font><font>,
    </font><font>"build_hash"</font><font> : </font><font>"04711c2"</font><font>,
    </font><font>"build_date"</font><font> : </font><font>"2018-09-26T13:34:09.098244Z"</font><font>,
    </font><font>"build_snapshot"</font><font> : false,
    </font><font>"lucene_version"</font><font> : </font><font>"7.4.0"</font><font>,
    </font><font>"minimum_wire_compatibility_version"</font><font> : </font><font>"5.6.0"</font><font>,
    </font><font>"minimum_index_compatibility_version"</font><font> : </font><font>"5.0.0"</font><font>
  },
  </font><font>"tagline"</font><font> : </font><font>"You Know, for Search"</font><font>
}
</font>

现在让我们使用默认的spring配置文件启动applicationn:

$ java -jar target/demo-0.0.1-SNAPSHOT.jar

然后让我们重复调用REST端点,将数据加载到ES中并查询:

curl http:<font><i>//localhost:8080/prepareData</i></font><font>
Data saved into elastic search!

$ curl http:</font><font><i>//localhost:8080/get/1</i></font><font>
{</font><font>"id"</font><font>:</font><font>"1"</font><font>,</font><font>"dataExchangeCode"</font><font>:</font><font>"AW_INPUT"</font><font>,</font><font>"data"</font><font>:</font><font>"<XML>"</font><font>}

$ curl http:</font><font><i>//localhost:8080/get/2</i></font><font>
{</font><font>"id"</font><font>:</font><font>"2"</font><font>,</font><font>"dataExchangeCode"</font><font>:</font><font>"BSL_INPUT"</font><font>,</font><font>"data"</font><font>:</font><font>"<XML>"</font><font>}
</font>

连接到外部ES也可以正常工作。

原文源码点击标题

原文  https://www.jdon.com/51369
正文到此结束
Loading...