首页 > 解决方案 > Spring Boot:使用 Rest 模板管理多个端点?

问题描述

在我的 Spring Boot 项目中,我在 application-dev.yml 文件中设置了几个端点(它们引用了一些 GET 或 POST REST API)。

spring:
    username: xxx
    password: acb132
    route:
      source:
        protocol: https://
        ip: 10.xxx.y.zz/
        root: "swdfr/"
        paths: >
            - "ofh/ert/hAFG5"
            - "ofh/ert/ryt54"

我想用一种方法在服务类中管理这些端点。目前我已经实现了这个解决方案:

//REST CONTROLLER
    @GetMapping("/Multiple_Get")
    public void manageGetEndpointsWithRestTemplate() throws Exception{
    final String methodName = "manageGetEndpointsWithRestTemplate()";
        try {
            service.manageGetEndpointsWithRestTemplate();
        } catch (final Exception e) {
            this.errorLog(methodName, e);
            throw e;
        }   
    }
    
//SERVICE
    @ResponseBody
    public void manageGetEndpointsWithRestTemplate() {
        final String methodName = "manageGetEndpointsWithRestTemplate()";
        try {
            String urlGet1 = protocol + ip + root + paths.get(0);
            String urlGet2 = protocol + ip + root + paths.get(1);

            HttpHeaders headers = new HttpHeaders();
            headers.setBasicAuth(username, password);
            HttpEntity request = new HttpEntity(headers);

            try {
                RestTemplate restTemplate;
                if (urlGet1.startsWith("https") || urlGet2.startsWith("https")) {
                    restTemplate = getRestTemplateForSelfSsl();
                } else {
                    restTemplate = new RestTemplate();
                }

                // GET1
                ResponseEntity<String> response1 = restTemplate.exchange(urlGet1, HttpMethod.GET, request,
                        String.class);
                HttpStatus statusCode1 = response1.getStatusCode();
                logger.info("STATUS GET1: " + statusCode1);
                
                // GET2
                ResponseEntity<String> response2 = restTemplate.exchange(urlGet2, HttpMethod.GET, request,
                        String.class);
                HttpStatus statusCode2 = response2.getStatusCode();
                logger.info("STATUS GET2: " + statusCode2);
                
            } catch (HttpStatusCodeException e) {
                logger.error(e.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

public RestTemplate getRestTemplateForSelfSsl()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] x509Certificates, String s) -> true;
    SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
            .build();
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    return restTemplate;
}

我想使用一种方法使其尽可能通用,尤其是在我必须管理大量端点的情况下。你有什么想法?提前致谢

标签: javaspring-bootresttemplateendpoint

解决方案


paths考虑到您正在GET对所有人进行请求,您可以遍历所有代码并执行通用代码。

@ResponseBody
public void manageGetEndpointsWithRestTemplate() {
    final String methodName = "manageGetEndpointsWithRestTemplate()";
    try {
        paths.forEach(path -> {
            String urlGet = protocol + ip + root + path;
            HttpHeaders headers = new HttpHeaders();
            headers.setBasicAuth(username, password);
            HttpEntity request = new HttpEntity(headers);
            try {
                RestTemplate restTemplate = urlGet.startsWith("https") ? getRestTemplateForSelfSsl() : new RestTemplate();
                ResponseEntity<String> response = restTemplate.exchange(urlGet, HttpMethod.GET, request,
                        String.class);
                HttpStatus statusCode = response.getStatusCode();
                logger.info("STATUS GET - {} : {}", urlGet, statusCode);
            } catch (HttpStatusCodeException e) {
                logger.error(e.getMessage());
            }
        });
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
}

如果您要使用POST或任何其他 HTTP 方法,请在application-dev.yml文件中与paths. 添加一些额外的逻辑来确定HTTP.XXX传递到restTemplate.exchange().


推荐阅读