Spring Boot基于AOP的本地/远程调用动态路由实践

01为什么我们要"无缝切换"

• MVP 阶段:单体最快,写完就可以上线。

• 流量暴涨后:微服务才能横向扩展,但把本地 userService.findById() 改成 feignClient.findById() 真要命------全链路改一遍,风险高、工期长。

• 理想状态:同一段业务代码,今天跑本地,明天改一行配置就跑远程,零代码侵入。

02核心设计一张图

java 复制代码
┌---------------┐
│  业务代码      │  ← 只认接口 UserService
└-------┬-------┘
        │ 注入
┌-------┴----------------┐
│  统一抽象层             │
│  根据配置动态选择实现    │
├------------┬-----------┤
│ UserServiceLocalImpl │ UserServiceRemoteImpl │
└------------┴-----------┘

03一步步落地

先画好契约------接口层

java 复制代码
// **统一接口** = 本地实现 + 远程 Feign 共用
public interface UserService {
    User getUserById(Long id);
    List<User> listAllUsers();
    User saveUser(User u);
    void updateUser(User u);
    void deleteUser(Long id);
}

本地实现

java 复制代码
@Service
@ConditionalOnProperty(name = "service.mode", havingValue = "local", matchIfMissing = true)
public class UserServiceLocalImpl implements UserService {

    @Autowired
    private UserRepository repo;   // 直连数据库,不走网络

    @Override
    public User getUserById(Long id) {
        return repo.findById(id).orElse(null);
    }

    @Override
    public List<User> listAllUsers() {
        return repo.findAll();
    }

    /* 其余方法省略 */
}

注解

  1. @ConditionalOnProperty:Spring Boot 的条件装配神器,配置文件里写 local 就激活。
  2. 直接依赖 DAO,零网络损耗,单元测试也能秒起。

远程实现------Feign

java 复制代码
// 1. 声明式 HTTP 客户端
@FeignClient(name = "user-service", fallback = UserServiceFallback.class)
public interface UserServiceFeignClient {

    @GetMapping("/api/users/{id}")
    User getUserById(@PathVariable("id") Long id);

    @GetMapping("/api/users")
    List<User> listAllUsers();

    @PostMapping("/api/users")
    User saveUser(@RequestBody User u);

    @PutMapping("/api/users")
    void updateUser(@RequestBody User u);

    @DeleteMapping("/api/users/{id}")
    void deleteUser(@PathVariable("id") Long id);
}
@Service
@ConditionalOnProperty(name = "service.mode", havingValue = "remote")
public class UserServiceRemoteImpl implements UserService {

    @Autowired
    private UserServiceFeignClient feignClient;   // 代理,真正发 HTTP

    @Override
    public User getUserById(Long id) {
        return feignClient.getUserById(id);
    }

    /* 其余方法省略 */
}

注解

  1. @FeignClient:Ribbon + Hystrix 自动集成,负载均衡、熔断降级开箱即用。
  2. fallback:远程挂了直接走兜底逻辑,雪崩不存在的。

自动配置

java 复制代码
@Configuration
@EnableFeignClients(basePackages = "com.example.feign")
public class ServiceAutoConfiguration {

    @Bean
    @ConditionalOnProperty(name = "service.mode", havingValue = "remote")
    public UserService userServiceRemote(UserServiceFeignClient client) {
        return new UserServiceRemoteImpl(client);
    }

    @Bean
    @ConditionalOnProperty(name = "service.mode", havingValue = "local", matchIfMissing = true)
    public UserService userServiceLocal(UserRepository repo) {
        return new UserServiceLocalImpl(repo);
    }
}

配置

java 复制代码
# application.yml
service:
  mode: local   # 改成 remote 秒变微服务

进阶玩法:细粒度路由 + 智能负载
按模块单独开关
service:
  user: local
  order: remote
  product: local

AOP 动态选路(伪代码)

java 复制代码
@Aspect
@Component
public class SmartRoutingAspect {
    @Around("@annotation(SmartRouting)")
    public Object route(ProceedingJoinPoint pjp) {
        // 统计 RT、错误率,实时计算 local vs remote 分值
        boolean goLocal = loadBalancingService.shouldGoLocal(pjp.getSignature());
        return goLocal ? pjp.proceed() : feignInvoke(pjp);
    }
}

05优缺点

相关推荐
打工仔折腾 AI4 分钟前
260+异构同步链路实战:如何用语义化自动翻译破解CDC DDL同步痛点
人工智能·后端·python·自然语言处理·性能优化·langchain·机器翻译
松就是我9029819 分钟前
Agent工具调用实现原理
后端
一枕槐安48722 分钟前
大模型应用后端设计:上下文管理、缓存、降级策略的工程方案总结
java·spring·缓存
T_Apollo22 分钟前
2.9 Java 25 版本新增特性和类
java
学习的老炮35 分钟前
反汇编基础速记
后端
步行cgn37 分钟前
@RequestMapping 注解详解
java·后端·spring
骑着蜗牛撵大象32738 分钟前
设备监控数据存与查:Spring Boot 接入 TimescaleDB 超表的完整落地
android·spring boot·后端·springboot·时序数据库·es·设备监控
鶴哥只手遮天38 分钟前
Spring Boot 4.1.1 深度源码解析-第 15 章 · 条件注解体系:全部 `@ConditionalOnXxx` 的实现原理
java·后端·开源
我的div丢了肿么办38 分钟前
go语言安装包详细讲解
后端·go
鶴哥只手遮天39 分钟前
Spring Boot 4.1.1 深度源码解析-第 30 章 · 基础设施能力:SSL Bundle、Task 与虚拟线程、Retry
java·后端·开源