簡體   English   中英

Spring Boot:使用 Rest 模板管理多個端點?

[英]Spring Boot: Manage Multiple Endpoint with Rest Template?

在我的 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;
}

我想使用一種方法使其盡可能通用,特別是如果我必須管理大量端點。 你有什么想法? 提前致謝

考慮到您正在為所有paths執行GET請求,您可以遍歷所有paths並執行公共代碼。

@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一起提及。 在傳遞到restTemplate.exchange()之前添加一些額外的邏輯來確定HTTP.XXX

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM