在我的项目中,我有很多微服务。最近,我已经从http更改为https。
我正在使用自定义RestTemplate
在SSLContext
中添加证书。
自定义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));
}
}