美文网首页
记-使用RestTemplate获取Elasticsearch数

记-使用RestTemplate获取Elasticsearch数

作者: 瓜尔佳_半阙 | 来源:发表于2018-08-23 10:48 被阅读272次

但是以这种方式获取到的ES数据需要解析好几层,没有用JPA或Java API来的直接

上代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;

@Repository
public class AppDownloadDao {

    @Value("${elasticsearch.api.url:}")
    private String misESHost;

    @Autowired
    private RestTemplate restTemplate;

    public ResponseEntity<String> getReleaseApp() {
        // ES 查询语句
        String requestStr = "{" +
                "    \"query\" : {" +
                "        \"bool\": {" +
                "            \"must\": [" +
                "                  { \"match\": { \"app\": \"hunter\"}}," +
                "                  { \"match\": { \"state\": \"2\"}}," +
                "                  { \"match\": { \"releaseFlag\": \"1\"}}" +
                "                  ]" +
                "        }" +
                "    }," +
                "    \"sort\": [" +
                "        {\"vcode\": \"desc\"}" +
                "    ]" +
                "}";
        // post方式请求数据
        return restTemplate.postForEntity(misESHost, getRequestBody(requestStr), String.class);
    }

    private synchronized <T> HttpEntity<T> getRequestBody(T requestStr) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        return new HttpEntity<>(requestStr, headers);
    }
}

参考:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html

相关文章

网友评论

      本文标题:记-使用RestTemplate获取Elasticsearch数

      本文链接:https://www.haomeiwen.com/subject/oljpiftx.html