Springboot4+httpservice完美代替openfeign
·
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
SpringBoot4.x发布后,http调用极大简化优雅,本章内容主要介绍基于springboot4.x下的http service调用方法。
本文章简单介绍使用入门,需要更加深入的使用请参考spring官方文档。
一、http service是什么?
基于spring-boot-starter-restclient/webclient组件的http服务调用工具箱,主要包含组件引入、http service定义、配置管理三部分组成。
二、使用步骤
1.引入库
代码如下(示例):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-restclient</artifactId>
</dependency>
2.httpservice定义
接口描述(示例):
package demo.httpservices;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
@HttpExchange
public interface DemoService{
@GetExchange(url = "/account/{userId}")
String queryInfo(@PathVariable Long userId);
}
相关配置(实例)
因项目结构要求,每个httpservice独立为分组,ImportHttpServices的参数只加group和value,也方便管理base-url、read-timeout等之类参数,这种配置更加灵活。
package demo.config;
import demo.httpservices.CentralSvcUnit;
import demo.httpservices.BaiduOSSClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.service.registry.ImportHttpServices;
@Configuration
@ImportHttpServices(group = "demo-service", value = DemoService.class)
@ImportHttpServices(group = "baidu-oss", value = BaiduOSSClient.class)
public class HttpRpcConfiguration {
}
最后一步是配置文件处理
spring:
threads:
virtual:
enabled: true
http:
#客户端统一配置
clients:
connect-timeout: 1s
read-timeout: 3s
# 公共配置区
serviceclient:
#基于内部服务发现的通用配置
demo-service:
base-url: http://127.0.0.1:9999/demo-service
read-timeout: 1s
# 百度云 OSS
#baidu-oss:
# base-url: http://kong:8000/baidu-oss-outernal
# read-timeout: 10s
配置文件说明
- spring.threads.virtual.enabled的开关决定着项目是否启用虚拟线程,如果为true,则httpclient组件的executor自动使用虚拟线程
- 可观测性相关依赖可以逐步加上
总结
- http client无需依赖额外组件如openfeign、甚至原始库如httpclient、okhttp等,项目更加简洁
- jdk17+后,开启虚拟线程,IO密集型应用吞吐量得到极大提升
- 统一规范、无需二次封装开箱即用,降低人员使用门槛
更多推荐




所有评论(0)