基于动态代理的rpc简单实现 aop 、proxy

发布时间 2023-09-05 16:07:12作者: 蜗牛无敌

1、实现注解

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)
public @interface XglConfig {
    String value() default "";
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface XgMapper {
    String value() default "";
}

2、接口定义

@XglConfig("http://www.baidu.com")
public interface UserServiceRpc {
    @XgMapper(value = "/getUser")
    Object getUser(String a);

    @XgMapper(value = "/getPayment")
    Object getPayment(String a);
}

3、代理逻辑

class RemoteServiceProxy implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 在这里可以添加远程调用的逻辑
        System.out.println("远程调用之前...");
        XglConfig annotation = method.getDeclaringClass().getAnnotation(XglConfig.class);
        if(annotation==null){
            return "";
        }
        String url = annotation.value();

        XgMapper annotation1 = method.getAnnotation(XgMapper.class);
        if(annotation1!=null){
            url = url + annotation1.value();
        }
        if(args!=null){

            // 获取参数名称数组
            Parameter[] parameterNames = method.getParameters();
            url = url + "?";
            for (int i = 0; i < args.length; i++) {
                url = url+parameterNames[i].getName()+"="+ args[i]+"&";
            }



        }

        System.out.println("远程调用之后...");
        return url;
    }
}

 

4、测试代理

 

    public static void main(String[] args) {

        // 创建动态代理对象
        UserServiceRpc proxy = (UserServiceRpc) Proxy.newProxyInstance(
                UserServiceRpc.class.getClassLoader(),
                new Class<?>[]{UserServiceRpc.class},
                new RemoteServiceProxy()
        );

        // 调用远程服务方法
        Object str = proxy.getPayment("wangwu");
        System.out.printf("=="+str);
    }

 还可以封装成代理工厂

public class RemoteServiceProxyFactory {
    public static  <T> T getInstance(Class<T> type){
      return (T)Proxy.newProxyInstance(
                RemoteServiceProxyFactory.class.getClassLoader(),
                new Class<?>[]{type},
                new RemoteServiceProxy()
        );

    }
}

 

测试

        UserServiceRpc proxy =  RemoteServiceProxyFactory.getInstance(UserServiceRpc.class);

        // 调用远程服务方法
        Object str = proxy.getPayment("wangwu");
        System.out.printf("=="+str);