springboot+es

springboot-es

本文 :Elasticsearch 与 sprigboot 的结合,springboot 操作es
关于es 的介绍和初识 可以看 https://blog.csdn.net/u012373815/article/details/50460248
安装
https://blog.csdn.net/u012373815/article/details/50463792

配置依赖

新建springboot项目 配置pom.xml 文件

   <dependency>
            <groupId>com.sun.jna</groupId>
            <artifactId>jna</artifactId>
            <version>3.0.9</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>rest</artifactId>
            <version>5.5.3</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.40</version>
        </dependency>

新建配置文件ESRestClientConfig

配置es 链接

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author yyb
 * @time 2019/4/2
 */
@Configuration
public class ESRestClientConfig {
    @Value("${elasticsearch.userName}")
    private String userName;
    @Value("${elasticsearch.password}")
    private String password;
    @Value("${elasticsearch.rest.hostNames}")
    private String hostName;
    @Value("${elasticsearch.rest.port}")
    private Integer port;

    @Bean(destroyMethod = "close")
    public RestClient getRestClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));
        RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(hostName, port));
        //配置身份验证
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });
        return restClientBuilder.build();
    }
}

在application.properties 文件中配置es 的链接

#es服务器地址配置
elasticsearch.userName=
elasticsearch.password=
elasticsearch.rest.hostNames=127.0.0.1
elasticsearch.rest.port=9200

使用es rest API 操作es

拼接查询query

首先要拼接 es 查询使用的 query

{
  "query": { 
  		"item": {
  			"userId": {
  				"value":"xxx"
  						}
  			 	}
  		  }
}

我在常量类中拼接

/**
 * @author yyb
 * @time 2019/4/3
 */
public class Constants {

    /**
     * es 查询query 拼接 前缀
     */
    public static final String ES_QUERY_JSON_PREFIX = "{\n" +
            "  \"query\": {\n" +
            "    \"term\": {\n" +
            "      \"userId\": {\n" +
            "        \"value\": \"";
    /**
     * es 查询query 拼接后缀
     */
    public static final String ES_QUERY_JSON_SUFFIX = "\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}\n";

 	/**
     * 需要查询的es的 index
     */
    public static final String ES_INDEX_PATH = "/logstash_indes/_search";

使用

在service 中使用 responseJson 为从es 中查询出来的结果。从json 中提取自己需要的信息

public User getById(Integer id) throws Exception {
        //拼接es 的查询query
        String json = Constants.ES_QUERY_JSON_PREFIX + id + Constants.ES_QUERY_JSON_SUFFIX;
        HttpEntity entry = new NStringEntity(json, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(HttpGet.METHOD_NAME, Constants.ES_INDEX_PATH, Collections.emptyMap(), entry);
        JSONObject responseJson = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
        //es 中查询的结果
        System.out.println(responseJson);
        return userDao.getById(id);
    }

本文完整源代码:https://github.com/527515025/springBoot/tree/master/springboot-elasticsearch

展开阅读全文
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值