微服务 feign 调用https
时间: 2023-09-25 21:10:44 浏览: 143
微服务之间的调用,也可以使用Feign来进行,同样需要在Feign的配置中启用HTTPS支持。具体步骤如下:
1. 引入Feign的依赖
```
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
```
2. 配置Feign的HTTPS支持
```
@Configuration
public class FeignConfig {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Client feignClient() {
return new Client.Default(getSSLSocketFactory(), null);
}
private SSLSocketFactory getSSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
} }, new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Bean
public Decoder feignDecoder() {
return new ResponseEntityDecoder(new SpringDecoder(messageConverters));
}
}
```
其中,`getSSLSocketFactory`方法返回一个`SSLSocketFactory`对象,用于创建HTTPS连接。这里采用了忽略证书的方式,实际生产环境中应该使用可信的证书。
3. 在Feign的接口中使用`https`协议
```
@FeignClient(name = "example", url = "https://example.com")
public interface ExampleClient {
@GetMapping("/api")
String get();
}
```
其中,`url`参数指定了HTTPS协议的地址。
4. 在微服务中使用Feign进行调用
```
@RestController
public class ExampleController {
@Autowired
private ExampleClient exampleClient;
@GetMapping("/example")
public String get() {
return exampleClient.get();
}
}
```
这样就可以在微服务中使用Feign调用HTTPS接口了。
阅读全文