百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

都说Feign是RPC,没有侵入性,为什么我的代码越来越像 C++

liuian 2025-05-27 15:54 4 浏览

1. 概览

随着 Spring Cloud 的流行性,Feign 已经成为 RPC 的事实标准,由于其构建与 Http 协议之上,对请求和返回值缺少规范约束,在日常开发过程中经常由于设计不当对系统造成一定的侵入性。比如,很多公司基于 Web 经验对 Feign 返回体进行了约束,大致要求如下:

  1. 所有的请求统一返回统一的 FeignResult
  2. FeignResult 中的 code 代表处理状态,msg 代表异常信息,data 代表返回结果
  3. 所有请求统一返回 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 码,降低繁琐的模板代码。

  1. 区分 Web 和 Feign 请求,只对 Feign 请求进行处理
  2. 正常返回结果,不受任何影响
  3. 异常返回结果,直接抛出异常,在异常中保存详细的 code 和 msg 信息
  4. 可自定义异常,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 的注册,主要包括:

  1. RpcRequestInterceptor。为 Feign 调用添加标记头
  2. RpcHandlerExceptionResolver。对 Feign 调用进行异常处理
  3. RpcErrorDecoder。Feign 调用发生异常后,从 RpcErrorResult 恢复异常
  4. 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);
        });
    }
}

执行单元测试,顺利通过,从测试结果中我们可得:

  1. 对于正常调用 postData 和 getData 方法,调用成功返回预期结果
  2. 对于异常调用 postDataForError 和 getDataForError 方法,直接抛出 RpcException

2.4. 定制异常

定制异常需要两个组件配合使用:

  1. CodeBasedException。在 Service 端使用,用于提供异常 code 和 msg 信息;
  2. 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 的组件进行定制,包括:

  1. RpcRequestInterceptor 实现 RequestInterceptor 接口。拦截 Feign 调用,在请求 Header 中添加 Feign 标签,用以标记该请求来自 Feign 调用
  2. RpcHandlerExceptionResolver 实现 HandlerExceptionResolver 接口。对 Spring MVC 出现的异常进行拦截,将异常信息转换为 RpcErrorResult 进行返回
  3. RpcErrorDecoder 实现 ErrorDecoder 接口。当请求返回码非 200 时进行调用,将 RpcErrorResult 转换为 RpcException 直接抛出

整个处理流程如下:

  1. 客户端调用 FeignClient 向 Server 发出请求,RpcRequestInterceptor 在请求头上添加标记 FeignRpc= YES
  2. 请求被 Spring MVC 的前置分发器 DispatcherServlet 处理
  3. DispatcherServlet 基于 HttpMessageConverter 将请求转换为方法参数,并调用业务方法;
  4. 如果业务方法调用成功
    1. HttpMessageConverter 将结果转化为 Json 并返回给客户端;
    2. FeignClient 的 Decoder 将 Json 转化为最终结果返回给调用方;
    3. 调用方成功拿到正常返回值
  5. 如果业务方法调用失败,抛出异常
    1. 异常被 RpcHandlerExceptionResolver 拦截
    2. RpcHandlerExceptionResolver 将 Exception 转化为 RpcErrorResult 并返回给客户端
    3. 异常返回码被 FeignClient 的 RpcErrorDecoder 拦截
    4. RpcErrorDecoder 读取 RpcErrorResult,并将其封装为 RpcException 直接抛出
    5. 调用方捕获异常进行处理

4. 项目信息

项目仓库地址:
https://gitee.com/litao851025/lego

项目文档地址:
https://gitee.com/litao851025/lego/wikis/support/feign

相关推荐

那些Java架构师必知必会的技术

Java基础#Java对象的内存布局MapStruct解了对象映射的毒周末我把HashMap源码又过了一遍Java7和Java8中的ConcurrentHashMap原理解析Java中自定...

Java内存泄漏最全详解(6大原因及解决方案)

大家好,我是mikechen。内存泄漏是经常出现的线上故障,也是大厂面试经常考察的,下面我就全面来详解内存泄漏以及解决方案@mikechen本篇已收于mikechen原创超30万字《阿里架构师进阶专题...

都说Feign是RPC,没有侵入性,为什么我的代码越来越像 C++

1.概览随着SpringCloud的流行性,Feign已经成为RPC的事实标准,由于其构建与Http协议之上,对请求和返回值缺少规范约束,在日常开发过程中经常由于设计不当对系统造成一...

面试题系列-java后端面试题List 和 Set 的区别

List和Set的区别List,Set都是继承自Collection接口List特点:元素有放入顺序,元素可重复,Set特点:元素无放入顺序,元素不可重复,重复元素会覆盖掉,(...

一直不理解为什么在重写equals方法时都要重写hashCode方法

为什么在重写equals方法时都要重写hashCode方法呢?首先jdk的要求是这样的,equals与hashcode间的关系:1、如果两个对象相同(即用equals比较返回true),那么它们的ha...

翻了ConcurrentHashMap1.7 和1.8的源码,我总结了它们的主要区别

ConcurrentHashMap思考:HashTable是线程安全的,为什么不推荐使用?HashTable是一个线程安全的类,它使用synchronized来锁住整张Hash表来实现线程安全,即每次...

10 个经典的 Java 集合面试题,看你能否答得上来?

来自:evget.com/article/2014/11/27/21869.html这里有10个经典的Java面试题,也为大家列出了答案。这是Java开发人员面试经常容易遇到的问题,相信你了解和掌握之...

MyBatis3.5.11-从入门到高阶

一.课程介绍MyBatis概述MyBatis基础应用MyBatis高级MyBatis进阶二.MyBatis概述1、为什么需要MyBatis在我们程序中,运行时期产生的数据都是存放在内存中的,那么在内存...

灵魂拷问:如何检查 Java 数组中是否包含某个值?

作者|沉默王二责编|Elle在逛programcreek的时候,我发现了一些专注细节但价值连城的主题。比如说:如何检查Java数组中是否包含某个值?像这类灵魂拷问的主题,非常值得深入地研...

Java后端学习路线是什么?

关于Java后端(SpringBoot为主)学习路线:一、Java基础阶段编程语言基础掌握基本数据类型(如int、double、char等)、变量、常量的定义和使用。理解运算符(算术、关...

Mybatis配置文件XML全貌详解,再不懂我也没招了

一、为什么要使用配置文件试想,如果没有配置文件,我们的应用程序将只能沿着固定的姿态运行,几乎不能做任何动态的调整,那么这不是一套完美的设计,因为我们希望拥有更宽更灵活的操作空间和更多的兼容度,同时也能...

软件性能调优全攻略:从瓶颈定位到工具应用

性能调优是软件测试中的重要环节,旨在提高系统的响应时间、吞吐量、并发能力、资源利用率,并降低系统崩溃或卡顿的风险。通常,性能调优涉及发现性能瓶颈、分析问题根因、优化代码和系统配置等步骤,调优之前需要先...

你还在使用Guava的Lists.newArrayList()吗

Guava说起Guava,做Java开发的应该没人不知道吧,毕竟“google出品,必属精品”。虽然应该没有Spring那样让Javaer无法避开,但是其中很多工具类的封装还是让人欲罢不能。而我们今天...

JDK成长记7:3张图搞懂HashMap底层原理

HashMap基本原理和优缺点HashMap基本原理和优缺点一句话讲,HashMap底层数据结构,JDK1.7数组+单向链表、JDK1.8数组+单向链表+红黑树。HashMap的3个底层原理Hash...

如何深度理解mybatis?

深度自定义mybatis回顾mybatis的操作的核心步骤编写核心类SqlSessionFacotryBuild进行解析配置文件深度分析解析SqlSessionFacotryBuild干的核心工作编写...