本文將基于前面構建的 RPC 能力,嘗試將其與 Spring Boot 整合,借助注解、自動掃描、依賴注入等機制,打造“開箱即用”的 Netty RPC 框架,提升開發效率與工程規范。
一、為什么要整合 Spring Boot?
手動 new 實例、寫注冊邏輯、寫接口代理代碼太繁瑣,不利于實際項目使用。我們希望:
-
通過注解快速暴露服務(類似 @RestController)
-
通過注解快速引用遠程服務(類似 @FeignClient)
-
自動初始化注冊中心、Netty 客戶端、服務端
? 本文目標:打造注解驅動、自動裝配的 RPC 框架
二、目標效果
// 暴露遠程服務
@RpcService
public class HelloServiceImpl implements HelloService {public String hello(String name) {return "Hello " + name;}
}// 注入遠程調用代理
@RpcReference
private HelloService helloService;
三、自定義注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface RpcService {String name() default "";
}@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RpcReference {String name() default "";
}
四、定義配置類與自動掃描器
我們通過 Spring Boot 的 @Import 加載注冊邏輯:
@Configuration
@ComponentScan("com.example.rpc")
@Import(RpcBeanPostProcessor.class)
public class RpcAutoConfiguration {
}
RpcBeanPostProcessor 掃描所有 @RpcService 和 @RpcReference 注解:
public class RpcBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {private ApplicationContext context;@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) {if (bean.getClass().isAnnotationPresent(RpcService.class)) {// 注冊服務到注冊中心 + 啟動 Netty 服務端RpcServer.register(bean);}for (Field field : bean.getClass().getDeclaredFields()) {if (field.isAnnotationPresent(RpcReference.class)) {Object proxy = RpcClient.createProxy(field.getType());field.setAccessible(true);try {field.set(bean, proxy);} catch (IllegalAccessException e) {throw new RuntimeException(e);}}}return bean;}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) {this.context = applicationContext;}
}
五、Spring Boot 項目結構建議
rpc-core/├── RpcClient.java├── RpcServer.java├── RpcProxy.java├── annotation/├── processor/
rpc-spring-boot-starter/├── RpcAutoConfiguration.java├── META-INF/spring.factories
demo-provider/├── HelloServiceImpl.java
demo-consumer/├── HelloController.java
只需在 pom.xml 引入:
<dependency><groupId>com.example</groupId><artifactId>rpc-spring-boot-starter</artifactId><version>1.0.0</version>
</dependency>
六、使用示例
服務端:
@SpringBootApplication
public class RpcProviderApp {public static void main(String[] args) {SpringApplication.run(RpcProviderApp.class, args);}
}
@RpcService
public class HelloServiceImpl implements HelloService {public String hello(String name) {return "Hello from Provider: " + name;}
}
客戶端:
@SpringBootApplication
public class RpcConsumerApp {public static void main(String[] args) {SpringApplication.run(RpcConsumerApp.class, args);}@RpcReferenceprivate HelloService helloService;@PostConstructpublic void init() {System.out.println(helloService.hello("Netty"));}
}
七、總結
通過本文,我們將 Netty RPC 框架成功整合進了 Spring Boot:
? 實現了服務自動注冊
? 注解式遠程調用
? 自動代理 + 自動注入
? 框架模塊化、可復用、可發布