1. 程式人生 > >Java遠程過程調用基礎:構建可自適應的動態代理對象的通用方法

Java遠程過程調用基礎:構建可自適應的動態代理對象的通用方法

Java RPC 動態代理

[toc]


Java遠程過程調用基礎:構建可自適應的動態代理對象的通用方法

前言

關於動態代理的知識,這裏不再過多說明。這裏要介紹的是,如何創建一個可自適應任意接口的動態代理對象的通用方法,也就是說,引用對象可為任意接口,舉個例子,假如返回動態代理對象的方法是getProxy,而同時存在兩個接口UserInterfaceProductInterface,這時可以這樣使用:

UserInterface user = getProxy(UserInterface.class);
ProductInterface product = getProxy(ProductInterface.class);

即不管接口類型是什麽,都可以使用getProxy()方法來創建動態代理對象,創建這樣一個方法的意義對於構建自己的RPC框架是非常重大的,因為實際可以在getProxy()方法中嵌入遠程過程調用客戶端的代碼,向服務端發出遠程調用的請求,以實現遠程過程調用的目的。

通用方法getProxy()

代碼如下:

    @SuppressWarnings("unchecked")
    public static <T> T getProxy(Class<?> interfaceClass) {
        T proxy = (T) Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class<?>[]{interfaceClass}, new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                System.out.println("調用的方法名是:" + methodName);
                return null;
            }
        });

        return proxy;
    }

測試

假如這裏有兩個接口,分別為UserInterfaceProductInterface,代碼如下:

UserInterface

package cn.xpleaf.service;

public interface UserInterface {

    public void getUsername();
}

ProductInterface

package cn.xpleaf.service;

public interface ProductInterface {

    public void getProduct();
}

測試代碼如下:

    @Test
    public void testGetProxy() {
        UserInterface user = getProxy(UserInterface.class);
        ProductInterface product = getProxy(ProductInterface.class);

        user.getUsername();
        product.getProduct();
    }

輸出結果如下:

調用的方法名是:getUsername
調用的方法名是:getProduct

實際應用

後面在進行開發RPC框架時將會充分用到這個通用的方法,在invoke方法中,就可以嵌入我們向服務端發送遠程調用請求的代碼,從而實現遠程調用的目的,而底層通信可以使用socket,當然也可以前面一直在探索的netty,不過出於性能上的考慮,當然會首選netty。

Java遠程過程調用基礎:構建可自適應的動態代理對象的通用方法