RestTemplate无法与@LoadBalanced一起使用

时间:2018-08-02 11:12:35

标签: java spring-boot load-balancing netflix-eureka

在我的项目中,我有很多微服务。最近,我已经从http更改为https。 我正在使用自定义RestTemplateSSLContext中添加证书。

自定义RestTemplate在没有@LoadBalanced的情况下可以正常工作,但是当我使用此注释时,会出现ConnectionRefused异常。

默认的RestTemplate@LoadBalanced批注可以很好地工作。

这是我的鳕鱼

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.net.ssl.SSLContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class Config {

    public static void copyStream(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
    }

    ClassPathResource classPathResource = new ClassPathResource("keypair.jks");

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() throws Exception {

        ClassPathResource classPathResource = new ClassPathResource("keypair.jks");

        InputStream inputStream = classPathResource.getInputStream();
        File certs = File.createTempFile("keypair", ".jks");

        FileOutputStream out = new FileOutputStream(certs);
        copyStream (inputStream, out);
        out.close();

//      return new RestTemplate();
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(certs)
//            .loadTrustMaterial(classPathResource.getFile())
                .build();
        CloseableHttpClient client = HttpClientBuilder.create().setSslcontext(sslContext).build();
        return new RestTemplate(new HttpComponentsClientHttpRequestFactory(client));
    }
}

0 个答案:

没有答案