都说Feign是RPC,没有侵入性,为什么我的代码越来越像 C++
ztj100 2024-12-29 07:22 26 浏览 0 评论
1. 概览
随着 Spring Cloud 的流行性,Feign 已经成为 RPC 的事实标准,由于其构建与 Http 协议之上,对请求和返回值缺少规范约束,在日常开发过程中经常由于设计不当对系统造成一定的侵入性。比如,很多公司基于 Web 经验对 Feign 返回体进行了约束,大致要求如下:
- 所有的请求统一返回统一的 FeignResult
- FeignResult 中的 code 代表处理状态,msg 代表异常信息,data 代表返回结果
- 所有请求统一返回 200,详细处理状态存储于 code
看规范定义,可以断定其出自于 Web 开发规范,但在使用过程中却为系统增加了太多的模板代码。
1.1. 背景
基于 Web 规范的 Feign 开发,让我们又回到了 C++ 时代,每次进行调用后,第一件事就是对 code 进行判断,示例如下:
public boolean login(Long userId){
FeignResult<User> userFeignResult = this.userFeignClient.getByUserId(userId);
if (userFeignResult.getCode() != SUCCESS){
throw new BizException(userFeignResult.getMsg());
}
User user = userFeignResult.getData();
return user.checkPassword(userId);
}
在拿到异常code后,往往读取 msg,然后抛出 自定义异常,从而中断处理流程。这些代码分布在系统的各处,枯燥无味还降低了代码的可读性。
对此,更加怀念 Dubbo 的做法,在 Client 和 Server 实现异常的穿透,最大限度的模拟 接口调用,让开发人员从重复代码中释放出来。
1.2. 目标
实现 Client 和 Server 间的异常穿透,使用 Java Exception 替代 Error Code 码,降低繁琐的模板代码。
- 区分 Web 和 Feign 请求,只对 Feign 请求进行处理
- 正常返回结果,不受任何影响
- 异常返回结果,直接抛出异常,在异常中保存详细的 code 和 msg 信息
- 可自定义异常,Client 调用失败时,抛出自定义异常
2. 快速入门
2.1. 准备环境
首先,引入 lego starter,在pom中增加依赖:
<groupId>com.geekhalo.lego</groupId>
<artifactId>lego-demo</artifactId>
<version>0.1.16-feign-SNAPSHOT</version>
FeignClientConfiuration 将自动完成核心 Bean 的注册,主要包括:
- RpcRequestInterceptor。为 Feign 调用添加标记头
- RpcHandlerExceptionResolver。对 Feign 调用进行异常处理
- RpcErrorDecoder。Feign 调用发生异常后,从 RpcErrorResult 恢复异常
- SimpleRpcExceptionResolver。将 RpcErrorResult 转化为 RpcException
2.2. 编写测试 Feign
首先,定义一个标准的 FeignApi ,具体如下:
public interface TestFeignApi {
@PostMapping("/test/postData/{key}")
void postData(@PathVariable String key, @RequestBody List<Long> data);
@PostMapping("/test/postDataForError/{key}")
void postDataForError(@PathVariable String key, @RequestBody List<Long> data);
@GetMapping("/test/getData/{key}")
List<Long> getData(@PathVariable String key);
@GetMapping("/test/getDataForError/{key}")
List<Long> getDataForError(@PathVariable String key);
}
基于 TestFeignApi 实现 TestFeignClient,具体如下:
@FeignClient(name = "testFeignClient", url = "http://127.0.0.1:9090")
public interface TestFeignClient extends TestFeignApi{
}
最后,构建 TestFeignApi 实现 TestFeignService,具体如下:
@RestController
public class TestFeignService implements TestFeignApi{
@Getter(AccessLevel.PRIVATE)
public Map<String, List<Long>> cache = Maps.newHashMap();
public List<Long> getByKey(String key){
return this.cache.get(key);
}
@Override
public void postData(String key, List<Long> data) {
this.cache.put(key, data);
}
@Override
public void postDataForError(String key, List<Long> data) {
throw new TestPostException();
}
@Override
public List<Long> getData(String key) {
return this.cache.get(key);
}
@Override
public List<Long> getDataForError(String key) {
throw new TestGetException();
}
}
2.3. 编写测试代码
编写单元测试如下:
@SpringBootTest(classes = DemoApplication.class, webEnvironment = DEFINED_PORT)
class TestFeignClientTest {
@Autowired
private TestFeignClient testFeignClient;
@Autowired
private TestFeignService testFeignService;
private String key;
private List<Long> data;
@BeforeEach
void setUp() {
this.key = String.valueOf(RandomUtils.nextLong());
this.data = Arrays.asList(RandomUtils.nextLong(), RandomUtils.nextLong(), RandomUtils.nextLong(), RandomUtils.nextLong());
}
@AfterEach
void tearDown() {
}
@Test
void postData(){
this.testFeignClient.postData(key, data);
Assertions.assertEquals(data, this.testFeignService.getData(key));
}
@Test
void postDataForError(){
Assertions.assertThrows(RpcException.class, ()->{
this.testFeignClient.postDataForError(key, data);
});
}
@Test
void getData(){
this.testFeignClient.postData(key, data);
List<Long> data = this.testFeignService.getData(key);
Assertions.assertEquals(data, this.data);
List<Long> ds = this.testFeignClient.getData(key);
Assertions.assertEquals(ds, this.data);
}
@Test
void getDataForError(){
this.testFeignClient.getData(key);
Assertions.assertThrows(RpcException.class, ()->{
this.testFeignClient.getDataForError(key);
});
}
}
执行单元测试,顺利通过,从测试结果中我们可得:
- 对于正常调用 postData 和 getData 方法,调用成功返回预期结果
- 对于异常调用 postDataForError 和 getDataForError 方法,直接抛出 RpcException
2.4. 定制异常
定制异常需要两个组件配合使用:
- CodeBasedException。在 Service 端使用,用于提供异常 code 和 msg 信息;
- RpcExceptionResolver。在 Client 端使用,基于 RpcErrorResult 将 code 恢复为指定异常;
首先,创建 CustomException,具体如下:
public class CustomException extends RuntimeException
implements CodeBasedException {
public static final int CODE = 550;
@Override
public int getErrorCode() {
return CODE;
}
@Override
public String getErrorMsg() {
return "自定义异常";
}
}
CutomException 实现CodeBasedException 接口,并对 getErrorCode 和 getErrorMsg 两个方法进行重写。
然后,增加 CustomExceptionResolver,具体如下:
@Component
public class CustomExceptionResolver implements RpcExceptionResolver {
@Override
public Exception resolve(String methodKey, int status, String remoteAppName, RpcErrorResult errorResult) {
if (errorResult.getCode() == CustomException.CODE){
throw new CustomException();
}
return null;
}
}
CustomExceptionResolver 实现 RpcExceptionResolver 接口,对 CustomException.CODE 进行特殊处理,直接返回 CustomException。
最后,编写方法抛出 CustomException,具体如下:
@Override
public void customException() {
throw new CustomException();
}
最后,编写并运行单元测试,具体如下:
@Test
void customException(){
Assertions.assertThrows(CustomException.class, ()->{
this.testFeignClient.customException();
});
}
可见,客户端在调用时指教抛出 CustomException,而非 RpcException。
3. 设计&扩展
image
为了对异常的管理,我们对 Feign 和 Spring MVC 的组件进行定制,包括:
- RpcRequestInterceptor 实现 RequestInterceptor 接口。拦截 Feign 调用,在请求 Header 中添加 Feign 标签,用以标记该请求来自 Feign 调用
- RpcHandlerExceptionResolver 实现 HandlerExceptionResolver 接口。对 Spring MVC 出现的异常进行拦截,将异常信息转换为 RpcErrorResult 进行返回
- RpcErrorDecoder 实现 ErrorDecoder 接口。当请求返回码非 200 时进行调用,将 RpcErrorResult 转换为 RpcException 直接抛出
整个处理流程如下:
- 客户端调用 FeignClient 向 Server 发出请求,RpcRequestInterceptor 在请求头上添加标记 FeignRpc= YES
- 请求被 Spring MVC 的前置分发器 DispatcherServlet 处理
- DispatcherServlet 基于 HttpMessageConverter 将请求转换为方法参数,并调用业务方法;
- 如果业务方法调用成功
- HttpMessageConverter 将结果转化为 Json 并返回给客户端;
- FeignClient 的 Decoder 将 Json 转化为最终结果返回给调用方;
- 调用方成功拿到正常返回值
- 如果业务方法调用失败,抛出异常
- 异常被 RpcHandlerExceptionResolver 拦截
- RpcHandlerExceptionResolver 将 Exception 转化为 RpcErrorResult 并返回给客户端
- 异常返回码被 FeignClient 的 RpcErrorDecoder 拦截
- RpcErrorDecoder 读取 RpcErrorResult,并将其封装为 RpcException 直接抛出
- 调用方捕获异常进行处理
4. 项目信息
项目仓库地址:https://gitee.com/litao851025/lego
项目文档地址:https://gitee.com/litao851025/lego/wikis/support/feign
相关推荐
-
- SpringBoot如何实现优雅的参数校验
-
平常业务中肯定少不了校验,如果我们把大量的校验代码夹杂到业务中,肯定是不优雅的,对于一些简单的校验,我们可以使用java为我们提供的api进行处理,同时对于一些...
-
2025-05-11 19:46 ztj100
- Java中的空指针怎么处理?
-
#暑期创作大赛#Java程序员工作中遇到最多的错误就是空指针异常,无论你多么细心,一不留神就从代码的某个地方冒出NullPointerException,令人头疼。...
- 一坨一坨 if/else 参数校验,被 SpringBoot 参数校验组件整干净了
-
来源:https://mp.weixin.qq.com/s/ZVOiT-_C3f-g7aj3760Q-g...
- 用了这两款插件,同事再也不说我代码写的烂了
-
同事:你的代码写的不行啊,不够规范啊。我:我写的代码怎么可能不规范,不要胡说。于是同事打开我的IDEA,安装了一个插件,然后执行了一下,规范不规范,看报告吧。这可怎么是好,这玩意竟然给我挑出来这么...
- SpringBoot中6种拦截器使用场景
-
SpringBoot中6种拦截器使用场景,下面是思维导图详细总结一、拦截器基础...
- 用注解进行参数校验,spring validation介绍、使用、实现原理分析
-
springvalidation是什么在平时的需求开发中,经常会有参数校验的需求,比如一个接收用户注册请求的接口,要校验用户传入的用户名不能为空、用户名长度不超过20个字符、传入的手机号是合法的手机...
- 快速上手:SpringBoot自定义请求参数校验
-
作者:UncleChen来源:http://unclechen.github.io/最近在工作中遇到写一些API,这些API的请求参数非常多,嵌套也非常复杂,如果参数的校验代码全部都手动去实现,写起来...
- 分布式微服务架构组件
-
1、服务发现-Nacos服务发现、配置管理、服务治理及管理,同类产品还有ZooKeeper、Eureka、Consulhttps://nacos.io/zh-cn/docs/what-is-nacos...
- 优雅的参数校验,告别冗余if-else
-
一、参数校验简介...
- Spring Boot断言深度指南:用断言机制为代码构筑健壮防线
-
在SpringBoot开发中,断言(Assert)如同代码的"体检医生",能在上线前精准捕捉业务逻辑漏洞。本文将结合企业级实践,解析如何通过断言机制实现代码自检、异常预警与性能优化三...
- 如何在项目中优雅的校验参数
-
本文看点前言验证数据是贯穿所有应用程序层(从表示层到持久层)的常见任务。通常在每一层实现相同的验证逻辑,这既费时又容易出错。为了避免重复这些验证,开发人员经常将验证逻辑直接捆绑到域模型中,将域类与验证...
- SpingBoot项目使用@Validated和@Valid参数校验
-
一、什么是参数校验?我们在后端开发中,经常遇到的一个问题就是入参校验。简单来说就是对一个方法入参的参数进行校验,看是否符合我们的要求。比如入参要求是一个金额,你前端没做限制,用户随便过来一个负数,或者...
- 28个验证注解,通过业务案例让你精通Java数据校验(收藏篇)
-
在现代软件开发中,数据验证是确保应用程序健壮性和可靠性的关键环节。JavaBeanValidation(JSR380)作为一个功能强大的规范,为我们提供了一套全面的注解工具集,这些注解能够帮...
- Springboot @NotBlank参数校验失效汇总
-
有时候明明一个微服务里的@Validated和@NotBlank用的好好的,但就是另一个里不能用,这时候问题是最不好排查的,下面列举了各种失效情况的汇总,供各位参考:1、版本问题springbo...
- 这可能是最全面的Spring面试八股文了
-
Spring是什么?Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- node卸载 (33)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- exceptionininitializererror (33)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)