Java学习:手写一个简单Rpc框架

java

    • 一、Server
    • 二、Client
    • 三、运行结果

关于Rpc框架会用到动态代理,对动态代理不清楚可以看我另一篇文章:
动态代理

一、Server

1、先定义一个接口

package LearnRpc.Server;

public interface CalculatorService {

    int add(int a, int b);

}

2、再实现接口

//可以看到server端这边有接口的具体实现方法
package LearnRpc.Server;

public class CalculatorServiceImpl implements CalculatorService {

    @Override
    public int add(int a, int b) {
        return a + b;
    }
}

3、定义server端逻辑

  1. server端与client建立socket连接
  2. 通过socket的getinputStream得到客户端传过来的方法名和参数类型
  3. 通过反射得到本地add方法实例
  4. 通过反射的invoke执行本地add方法把结果返回出去

package LearnRpc.Server;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.ServerSocket;
import java.net.Socket;

public class RpcServer {

    public void export(Object service, int port) throws Exception {
        if (service == null) {
            throw new IllegalArgumentException("service instance == null");
        }
        if (port <= 0 || port > 65535) {
            throw new IllegalArgumentException("Invalid port " + port);
        }

        ServerSocket server = new ServerSocket(port);
        while (true) {
            final Socket socket = server.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
                        ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                        try {
                            String methodName = input.readUTF();
                            Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
                            Object[] arguments = (Object[]) input.readObject();
                            Method method = service.getClass().getMethod(methodName, parameterTypes);
                            Object result = method.invoke(service, arguments);
                            output.writeObject(result);
                        } catch (Throwable t) {
                            output.writeObject(t);
                        } finally {
                            output.close();
                            input.close();
                            socket.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

}

4、启动类

package LearnRpc.Server;

public class RpcServerApplication {

    public static void main(String[] args) throws Exception {
        CalculatorService service = new CalculatorServiceImpl();
        RpcServer server = new RpcServer();
        server.export(service, 1234);
    }

}

二、Client

1、先定义一个接口

package LearnRpc.Client;
//与server同样的接口,接口中有add方法,具体的实现在Server端那边
public interface CalculatorService {

    int add(int a, int b);

}

2、动态代理类

  1. 与server端建立socket连接
  2. 通过socket.getoutputStream把方法名和参数类型发送给server
  3. 提供代理类实例,这个代理类实例有一个专属名称-“桩",与远程服务具有相同的方法签名或者说实现了相同的接口,客户端在调用Rpc框架提供的服务时,实际上就是调用"桩”提供的方法,在桩的实现方法中,它会发请求的服务名和参数到客户端,服务端的Rpc框架收到请求后,解析出服务名和参数后,调用Rpc框架中真正的服务提供者,然后将结果返回给客户端
package LearnRpc.Client;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class RpcClient {

    public <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {

        if (interfaceClass == null)
            throw new IllegalArgumentException("Interface class == null");
        if (! interfaceClass.isInterface())
            throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");
        if (host == null || host.length() == 0)
            throw new IllegalArgumentException("Host == null!");
        if (port <= 0 || port > 65535)
            throw new IllegalArgumentException("Invalid port " + port);

        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
                Socket socket = new Socket(host, port);
                try {
                    ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                    try {
                        output.writeUTF(method.getName());
                        output.writeObject(method.getParameterTypes());
                        output.writeObject(arguments);
                        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
                        try {
                            Object result = input.readObject();
                            if (result instanceof Throwable) {
                                throw (Throwable) result;
                            }
                            return result;
                        } finally {
                            input.close();
                        }
                    } finally {
                        output.close();
                    }
                } finally {
                    socket.close();
                }
            }
        });
    }

}

3、客户端逻辑

package LearnRpc.Client;
/*
可以看到client没有接口中add的具体实现,但还是像调用本地add方法一样,
使用rpc可以屏蔽远程方法调用的细节
*/
public class ClientDemo {

    public static void main(String[] args) throws Exception {
        RpcClient client = new RpcClient();
        CalculatorService service = client.refer(CalculatorService.class, "127.0.0.1", 1234);
        int result = service.add(2, 8);
        System.out.println("result:" + result);
    }

}

三、运行结果

Java学习:手写一个简单Rpc框架_第1张图片

你可能感兴趣的:(Java开发,java,学习,rpc)