记-使用RestTemplate获取Elasticsearch数据

但是以这种方式获取到的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 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  HttpEntity 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数据)