SpringBoot中如何配置使用okhttp3进行网络请求操作?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1676个文字,预计阅读时间需要7分钟。
1. Maven 添加依赖: xml com.squareup.okhttp3 okhttp 3.10.0
2. application.properties 配置文件: properties ok.http.connect-timeout=30 ok.http.read-timeout=30 ok.http.write-timeout=
1. Maven 添加依赖
<dependency> <groupId>com.squareup.okwww.baidu.com/"; String message = okHttpCli.doGet(url); return message; } }
6. 双向认证(待证)
@Bean public SSLSocketFactory sslSocketFactory() { String certPath = ""; String caPath = ""; String certPwd = ""; String caPwd = ""; try { ClassPathResource selfcertPath = new ClassPathResource(certPath); ClassPathResource trustcaPath = new ClassPathResource(caPath); KeyStore selfCert = KeyStore.getInstance("pkcs12"); selfCert.load(selfcertPath.getInputStream(), certPwd.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509"); kmf.init(selfCert, certPwd.toCharArray()); KeyStore caCert = KeyStore.getInstance("jks"); caCert.load(trustcaPath.getInputStream(), caPwd.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509"); tmf.init(caCert); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); return sslContext.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); } return null; }
补充:Spring Cloud Feign 总结问题,注意点,性能调优,切换okIP:PORT/actuator/hystrix.stream 是会返回404,这是因为Feign虽然整合了Hystrix,但并没有整合Hystrix的监控。如何添加监控支持呢?需要以下几步:
第一步:添加依赖,示例:
<!-- 整合hystrix,其实feign中自带了hystrix,引入该依赖主要是为了使用其中的hystrix-metrics-event-stream,用于dashboard --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency>
第二步:在启动类上添加@EnableCircuitBreaker 注解,示例:
@SpringBootApplication @EnableFeignClients @EnableDiscoveryClient @EnableCircuitBreaker public class MovieFeignHystrixApplication { public static void main(String[] args) { SpringApplication.run(MovieFeignHystrixApplication.class, args); } }
第三步:在application.yml中添加如下内容,暴露hystrix.stream端点:
management: endpoints: web: exposure: include: 'hystrix.stream'
这样,访问任意Feign Client接口的API后,再访问IP:PORT/actuator/hystrix.stream ,就会展示一大堆Hystrix监控数据了。
Feign 上传文件
加依赖
<dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form-spring</artifactId> <version>3.0.3</version> </dependency>
编写Feign Client
@FeignClient(name = "ms-content-sample", configuration = UploadFeignClient.MultipartSupportConfig.class) public interface UploadFeignClient { @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseBody String handleFileUpload(@RequestPart(value = "file") MultipartFile file); class MultipartSupportConfig { @Bean public Encoder feignFormEncoder() { return new SpringFormEncoder(); } } }
如代码所示,在这个Feign Client中,我们引用了配置类MultipartSupportConfig ,在MultipartSupportConfig 中,我们实例化了SpringFormEncoder 。这样这个Feign Client就能够上传啦。
注意点
//RequestMapping注解中的produeces 、consumes 不能少; @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
接口定义中的注解@RequestPart(value = "file") 不能写成@RequestParam(value = "file") 。
最好将Hystrix的超时时间设长一点,例如5秒,否则可能文件还没上传完,Hystrix就超时了,从而导致客户端侧的报错。
Feign实现Form表单提交
添加依赖:
<dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form-spring</artifactId> <version>3.2.2</version> </dependency>
Feign Client示例:
@FeignClient(name = "xxx", url = "www.itmuch.com/", configuration = TestFeignClient.FormSupportConfig.class) public interface TestFeignClient { @PostMapping(value = "/test", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE} ) void post(Map<String, ?> queryParam); class FormSupportConfig { @Autowired private ObjectFactory<HttpMessageConverters> messageConverters; // new一个form编码器,实现支持form表单提交 @Bean public Encoder feignFormEncoder() { return new SpringFormEncoder(new SpringEncoder(messageConverters)); } // 开启Feign的日志 @Bean public Logger.Level logger() { return Logger.Level.FULL; } } }
调用示例:
@GetMapping("/user/{id}") public User findById(@PathVariable Long id) { HashMap<String, String> param = Maps.newHashMap(); param.put("username","zhangsan"); param.put("password","pwd"); this.testFeignClient.post(param); return new User(); }
日志:
...[TestFeignClient#post] ---> POST www.baidu.com/test HTTP/1.1 ...[TestFeignClient#post] Accept: application/json;charset=UTF-8 ...[TestFeignClient#post] Content-Type: application/x-www-form-urlencoded; charset=UTF-8 ...[TestFeignClient#post] Content-Length: 30 ...[TestFeignClient#post] ...[TestFeignClient#post] password=pwd&username=zhangsan ...[TestFeignClient#post] ---> END HTTP (30-byte body)
由日志可知,此时Feign已能使用Form表单方式提交数据。
Feign GET请求如何构造多参数
假设需请求的URL包含多个参数,例如microservice-provider-user/get?id=1&username=张三 ,该如何使用Feign构造呢?我们知道,Spring Cloud为Feign添加了Spring MVC的注解支持,那么我们不妨按照Spring MVC的写法尝试一下:
@FeignClient("microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/get", method = RequestMethod.GET) public User get0(User user); }
然而,这种写法并不正确,控制台会输出类似如下的异常。
feign.FeignException: status 405 reading UserFeignClient#get0(User); content: {"timestamp":1482676142940,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/get"}
由异常可知,尽管我们指定了GET方法,Feign依然会使用POST方法发送请求。于是导致了异常。正确写法如下
方法一[推荐]注意:使用该方法无法使用Fegin的继承模式
@FeignClient("microservice-provider-user") public interface UserFeignClient { @GetMapping("/get") public User get0(@SpringQueryMap User user); }
方法二[推荐]
@FeignClient(name = "microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/get", method = RequestMethod.GET) public User get1(@RequestParam("id") Long id, @RequestParam("username") String username); }
这是最为直观的方式,URL有几个参数,Feign接口中的方法就有几个参数。使用@RequestParam注解指定请求的参数是什么。
方法三[不推荐]多参数的URL也可使用Map来构建。当目标URL参数非常多的时候,可使用这种方式简化Feign接口的编写。
@FeignClient(name = "microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/get", method = RequestMethod.GET) public User get2(@RequestParam Map<String, Object> map); }
在调用时,可使用类似以下的代码。
public User get(String username, String password) { HashMap<String, Object> map = Maps.newHashMap(); map.put("id", "1"); map.put("username", "张三"); return this.userFeignClient.get2(map); }
注意:这种方式不建议使用。主要是因为可读性不好,而且如果参数为空的时候会有一些问题,例如map.put("username", null); 会导致服务调用方(消费者服务)接收到的username是"" ,而不是null。
切换为 Okhttp3 提升 QPS 性能优化
加依赖引入okhttp3
<dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-okhttp</artifactId> <version>${version}</version> </dependency>
写配置
feign: # feign启用hystrix,才能熔断、降级 # hystrix: # enabled: true # 启用 okhttp 关闭默认 httpclient httpclient: enabled: false #关闭httpclient # 配置连接池 max-connections: 200 #feign的最大连接数 max-connections-per-route: 50 #fegin单个路径的最大连接数 okhttp: enabled: true # 请求与响应的压缩以提高通信效率 compression: request: enabled: true min-request-size: 2048 mime-types: text/xml,application/xml,application/json response: enabled: true
参数配置
/** * 配置 okhttp 与连接池 * ConnectionPool 默认创建5个线程,保持5分钟长连接 */ @Configuration @ConditionalOnClass(Feign.class) @AutoConfigureBefore(FeignAutoConfiguration.class) //SpringBoot自动配置 public class OkHttpConfig { // 默认老外留给你彩蛋中文乱码,加上它就 OK @Bean public Encoder encoder() { return new FormEncoder(); } @Bean public okhttp3.OkHttpClient okHttpClient() { return new okhttp3.OkHttpClient.Builder() //设置连接超时 .connectTimeout(10, TimeUnit.SECONDS) //设置读超时 .readTimeout(10, TimeUnit.SECONDS) //设置写超时 .writeTimeout(10, TimeUnit.SECONDS) //是否自动重连 .retryOnConnectionFailure(true) .connectionPool(new ConnectionPool(10, 5L, TimeUnit.MINUTES)) .build(); } }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持易盾网络。如有错误或未考虑完全的地方,望不吝赐教。
本文共计1676个文字,预计阅读时间需要7分钟。
1. Maven 添加依赖: xml com.squareup.okhttp3 okhttp 3.10.0
2. application.properties 配置文件: properties ok.http.connect-timeout=30 ok.http.read-timeout=30 ok.http.write-timeout=
1. Maven 添加依赖
<dependency> <groupId>com.squareup.okwww.baidu.com/"; String message = okHttpCli.doGet(url); return message; } }
6. 双向认证(待证)
@Bean public SSLSocketFactory sslSocketFactory() { String certPath = ""; String caPath = ""; String certPwd = ""; String caPwd = ""; try { ClassPathResource selfcertPath = new ClassPathResource(certPath); ClassPathResource trustcaPath = new ClassPathResource(caPath); KeyStore selfCert = KeyStore.getInstance("pkcs12"); selfCert.load(selfcertPath.getInputStream(), certPwd.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509"); kmf.init(selfCert, certPwd.toCharArray()); KeyStore caCert = KeyStore.getInstance("jks"); caCert.load(trustcaPath.getInputStream(), caPwd.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509"); tmf.init(caCert); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); return sslContext.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); } return null; }
补充:Spring Cloud Feign 总结问题,注意点,性能调优,切换okIP:PORT/actuator/hystrix.stream 是会返回404,这是因为Feign虽然整合了Hystrix,但并没有整合Hystrix的监控。如何添加监控支持呢?需要以下几步:
第一步:添加依赖,示例:
<!-- 整合hystrix,其实feign中自带了hystrix,引入该依赖主要是为了使用其中的hystrix-metrics-event-stream,用于dashboard --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency>
第二步:在启动类上添加@EnableCircuitBreaker 注解,示例:
@SpringBootApplication @EnableFeignClients @EnableDiscoveryClient @EnableCircuitBreaker public class MovieFeignHystrixApplication { public static void main(String[] args) { SpringApplication.run(MovieFeignHystrixApplication.class, args); } }
第三步:在application.yml中添加如下内容,暴露hystrix.stream端点:
management: endpoints: web: exposure: include: 'hystrix.stream'
这样,访问任意Feign Client接口的API后,再访问IP:PORT/actuator/hystrix.stream ,就会展示一大堆Hystrix监控数据了。
Feign 上传文件
加依赖
<dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form-spring</artifactId> <version>3.0.3</version> </dependency>
编写Feign Client
@FeignClient(name = "ms-content-sample", configuration = UploadFeignClient.MultipartSupportConfig.class) public interface UploadFeignClient { @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseBody String handleFileUpload(@RequestPart(value = "file") MultipartFile file); class MultipartSupportConfig { @Bean public Encoder feignFormEncoder() { return new SpringFormEncoder(); } } }
如代码所示,在这个Feign Client中,我们引用了配置类MultipartSupportConfig ,在MultipartSupportConfig 中,我们实例化了SpringFormEncoder 。这样这个Feign Client就能够上传啦。
注意点
//RequestMapping注解中的produeces 、consumes 不能少; @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
接口定义中的注解@RequestPart(value = "file") 不能写成@RequestParam(value = "file") 。
最好将Hystrix的超时时间设长一点,例如5秒,否则可能文件还没上传完,Hystrix就超时了,从而导致客户端侧的报错。
Feign实现Form表单提交
添加依赖:
<dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form-spring</artifactId> <version>3.2.2</version> </dependency>
Feign Client示例:
@FeignClient(name = "xxx", url = "www.itmuch.com/", configuration = TestFeignClient.FormSupportConfig.class) public interface TestFeignClient { @PostMapping(value = "/test", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE} ) void post(Map<String, ?> queryParam); class FormSupportConfig { @Autowired private ObjectFactory<HttpMessageConverters> messageConverters; // new一个form编码器,实现支持form表单提交 @Bean public Encoder feignFormEncoder() { return new SpringFormEncoder(new SpringEncoder(messageConverters)); } // 开启Feign的日志 @Bean public Logger.Level logger() { return Logger.Level.FULL; } } }
调用示例:
@GetMapping("/user/{id}") public User findById(@PathVariable Long id) { HashMap<String, String> param = Maps.newHashMap(); param.put("username","zhangsan"); param.put("password","pwd"); this.testFeignClient.post(param); return new User(); }
日志:
...[TestFeignClient#post] ---> POST www.baidu.com/test HTTP/1.1 ...[TestFeignClient#post] Accept: application/json;charset=UTF-8 ...[TestFeignClient#post] Content-Type: application/x-www-form-urlencoded; charset=UTF-8 ...[TestFeignClient#post] Content-Length: 30 ...[TestFeignClient#post] ...[TestFeignClient#post] password=pwd&username=zhangsan ...[TestFeignClient#post] ---> END HTTP (30-byte body)
由日志可知,此时Feign已能使用Form表单方式提交数据。
Feign GET请求如何构造多参数
假设需请求的URL包含多个参数,例如microservice-provider-user/get?id=1&username=张三 ,该如何使用Feign构造呢?我们知道,Spring Cloud为Feign添加了Spring MVC的注解支持,那么我们不妨按照Spring MVC的写法尝试一下:
@FeignClient("microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/get", method = RequestMethod.GET) public User get0(User user); }
然而,这种写法并不正确,控制台会输出类似如下的异常。
feign.FeignException: status 405 reading UserFeignClient#get0(User); content: {"timestamp":1482676142940,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/get"}
由异常可知,尽管我们指定了GET方法,Feign依然会使用POST方法发送请求。于是导致了异常。正确写法如下
方法一[推荐]注意:使用该方法无法使用Fegin的继承模式
@FeignClient("microservice-provider-user") public interface UserFeignClient { @GetMapping("/get") public User get0(@SpringQueryMap User user); }
方法二[推荐]
@FeignClient(name = "microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/get", method = RequestMethod.GET) public User get1(@RequestParam("id") Long id, @RequestParam("username") String username); }
这是最为直观的方式,URL有几个参数,Feign接口中的方法就有几个参数。使用@RequestParam注解指定请求的参数是什么。
方法三[不推荐]多参数的URL也可使用Map来构建。当目标URL参数非常多的时候,可使用这种方式简化Feign接口的编写。
@FeignClient(name = "microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/get", method = RequestMethod.GET) public User get2(@RequestParam Map<String, Object> map); }
在调用时,可使用类似以下的代码。
public User get(String username, String password) { HashMap<String, Object> map = Maps.newHashMap(); map.put("id", "1"); map.put("username", "张三"); return this.userFeignClient.get2(map); }
注意:这种方式不建议使用。主要是因为可读性不好,而且如果参数为空的时候会有一些问题,例如map.put("username", null); 会导致服务调用方(消费者服务)接收到的username是"" ,而不是null。
切换为 Okhttp3 提升 QPS 性能优化
加依赖引入okhttp3
<dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-okhttp</artifactId> <version>${version}</version> </dependency>
写配置
feign: # feign启用hystrix,才能熔断、降级 # hystrix: # enabled: true # 启用 okhttp 关闭默认 httpclient httpclient: enabled: false #关闭httpclient # 配置连接池 max-connections: 200 #feign的最大连接数 max-connections-per-route: 50 #fegin单个路径的最大连接数 okhttp: enabled: true # 请求与响应的压缩以提高通信效率 compression: request: enabled: true min-request-size: 2048 mime-types: text/xml,application/xml,application/json response: enabled: true
参数配置
/** * 配置 okhttp 与连接池 * ConnectionPool 默认创建5个线程,保持5分钟长连接 */ @Configuration @ConditionalOnClass(Feign.class) @AutoConfigureBefore(FeignAutoConfiguration.class) //SpringBoot自动配置 public class OkHttpConfig { // 默认老外留给你彩蛋中文乱码,加上它就 OK @Bean public Encoder encoder() { return new FormEncoder(); } @Bean public okhttp3.OkHttpClient okHttpClient() { return new okhttp3.OkHttpClient.Builder() //设置连接超时 .connectTimeout(10, TimeUnit.SECONDS) //设置读超时 .readTimeout(10, TimeUnit.SECONDS) //设置写超时 .writeTimeout(10, TimeUnit.SECONDS) //是否自动重连 .retryOnConnectionFailure(true) .connectionPool(new ConnectionPool(10, 5L, TimeUnit.MINUTES)) .build(); } }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持易盾网络。如有错误或未考虑完全的地方,望不吝赐教。

