目录
GitHub地址
https://github.com/Asperger12345/shenrpc-spring-boot-starter
文件目录

Message
传递的消息载体类
package com.shen.api;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
@Data
@Builder
public class Message implements Serializable {
//服务接口名
private String className;
//方法名
private String methodName;
//参数
private Object[] args;
//接口类型
private Class[] types;
}
consumer
服务消费方
@EnableRpcConsumer
打在SpringBoot启动类上
package com.shen.api.consumer;
import org.springframework.context.annotation.Import;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import({
ReferenceInvokeProxy.class,RpcHandler.class})
public @interface EnableRpcConsumer {
}
@Reference
打在注入的接口上
package com.shen.api.consumer;
import org.springframework.stereotype.Component;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface Reference {
}
ReferenceInvokeProxy
对于每个有 @Reference 注解的接口,生成代理
package com.shen.api.consumer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
public class ReferenceInvokeProxy implements BeanPostProcessor {
@Autowired
RpcHandler invocationHandler;
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
Field[] fields=bean.getClass().getDeclaredFields();
for(Field field:fields){
if(field.isAnnotationPresent(Reference.class)){
field.setAccessible(true);
Object proxy= Proxy.newProxyInstance(field.getType().getClassLoader(),new Class<?>[]{
field.getType()},invocationHandler);
try {
field.set(bean,proxy);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return bean;
}
}

本文详细介绍了基于Spring Boot的远程过程调用(RPC)框架的设计与实现,包括服务消费者与提供者的注解、代理生成、BIO通信处理、服务注册与发现等关键组件。通过具体示例展示了如何在消费方和提供方应用该RPC框架。
最低0.47元/天 解锁文章
716

被折叠的 条评论
为什么被折叠?



