手写RPC

服务端代码

package com.peiyu.rpcs.bios;

import java.io.IOException;

public interface IRpcServers {

    void start() throws IOException;

    /**
     * 服务注册
     * @param serviceInterface 服务接口
     * @param impl 服务实现类
     */
    void register(Class serviceInterface, Class impl);
}

实现类

package com.peiyu.rpcs.bios;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class RpcServesrImpl implements IRpcServers {
    private int port;
    public static final HashMap<String, Class> serviceRegistry = new HashMap<String, Class>();
    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 20, 100, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(100));

    public RpcServesrImpl(int port) {
        this.port = port;
    }

    /**
     * 启动服务
     */
    @Override
    public void start() throws IOException {
        ServerSocket server = new ServerSocket();
        server.bind(new InetSocketAddress(port));
        System.out.println("Bio rpc 服务启动开始###端口###" + port);
        try {
            while (true) {
                System.out.println("等待客户端接入");
                executor.execute(new ServersTask(server.accept()));
            }
        } catch (Exception e) {
            if (server != null) {
                server.close();
            }
        }
    }

    @Override
    public void register(Class serviceInterface, Class impl) {
        serviceRegistry.put(serviceInterface.getName(), impl);
    }

    static class ServersTask implements Runnable {
        Socket client = null;

        public ServersTask(Socket socket) {
            this.client = socket;
        }

        ObjectInputStream input = null;//输入流
        ObjectOutputStream output = null;//输出流

        @Override
        public void run() {
            //接收客户端发送来的字节流,并转化成对象,反射调用服务实现者,获取执行结果
            try {
                input = new ObjectInputStream(this.client.getInputStream());
                String interfaceName = input.readUTF();
                String methodName = input.readUTF();
                Class<?>[] parameterType = (Class<?>[]) input.readObject();
                Object[] args = (Object[]) input.readObject();
                Class serverClass = serviceRegistry.get(interfaceName);//这里有问题服务器端去注册中心拉取实现类??
                                                                    //但是如果不考虑注册中心,当作本地映射还挺好,
                                                                    //省的使用反射来通过接口来找实现类.
                if (serverClass == null) {
                    throw new ClassNotFoundException(interfaceName + " not found");
                }
                Method method = serverClass.getMethod(methodName, parameterType);
                Object result = method.invoke(serverClass.newInstance(), args);
                //执行结果反序列化返回给客户端
                output = new ObjectOutputStream(this.client.getOutputStream());
                output.writeObject(result);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (this.client != null) {
                    try {
                        this.client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}

mainapp

package com.peiyu.rpcs.bios;

import java.io.IOException;

public class MainApp {
    public static void main(String[] args) throws Exception {
        IRpcServers server = new RpcServesrImpl(8080);
        server.register(IOrderService.class, IOrderServiceImpl.class);
        server.start();
    }

}

一个接口一个实现类

package com.peiyu.rpcs.bios;

public interface IOrderService {
    String getOrderDtoByUserId(int i);

}
package com.peiyu.rpcs.bios;

public class IOrderServiceImpl implements IOrderService{

    @Override
    public String getOrderDtoByUserId(int i) {
        // TODO Auto-generated method stub
        
        return 100*i+"";
    }

}

客户端

package com.peiyu.rpcs.bios;

public class CLIENT {
    public static void main(String[] args) {
    long start =System.currentTimeMillis();
    for (int i=0;i<200;i++){
        try {
            IOrderService orderService= ProxyFactory.create(IOrderService.class,"127.0.0.1",8080);
            System.out.println(orderService.getOrderDtoByUserId(i));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    long end=System.currentTimeMillis();
    System.out.println("总耗时:"+(end-start));

}

}

代理

package com.peiyu.rpcs.bios;

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 ProxyFactory<T> {

    public static <T> T create(final Class<?> serviceInterface, final String ip, final int port) {
        //将本地的接口调用转换成JDK的动态代理,在动态代理中实现接口的远程调用
        return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class<?>[]{serviceInterface}, new ProxyHandler(ip, port, serviceInterface));
    }

    static class ProxyHandler implements InvocationHandler {
        private String ip;
        private int port;
        private Class<?> serviceInterface;

        public ProxyHandler(String ip, int port, Class<?> serviceInterface) {
            this.ip = ip;
            this.port = port;
            this.serviceInterface = serviceInterface;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Socket socket = null;
            ObjectOutputStream output = null;
            ObjectInputStream input = null;
            try {
                // 创建Socket客户端,根据指定地址连接远程服务提供者
                socket = new Socket(ip, port);
                // 将远程服务调用所需的接口类、方法名、参数列表等编码后发送给服务提供者
                output = new ObjectOutputStream(socket.getOutputStream());
                output.writeUTF(serviceInterface.getName());
                output.writeUTF(method.getName());
                output.writeObject(method.getParameterTypes());
                output.writeObject(args);
                // 同步阻塞等待服务器返回应答,获取应答后返回
                input = new ObjectInputStream(socket.getInputStream());
                return input.readObject();
            } finally {
                if (socket != null) {
                    socket.close();
                }
                if (output != null) {
                    output.close();
                }
                if (input != null) {
                    input.close();
                }
            }
        }
    }
}

本地接口

package com.peiyu.rpcs.bios;

public interface IOrderService {
    String getOrderDtoByUserId(int i);

}

总结与注意点:

1:output.writeUTF(serviceInterface.getName());这里面是 包名+接口名

2:这个是网上的代码,有些问题,注册中心serviceRegistry = new HashMap<String, Class>();写在了服务端,应该是客户端拉取才对,是不是客户端传output.writeUTF(com.peiyu.rpcs.bios.IOrderServiceImpl);才对呢?我想是,待考证(错误)

3.这个RPC如果不用serviceRegistry 映射,则需要通过接口找到实现类,这个就很麻烦

补充: 从注册中心拉取的是

//从ZK中获取地址 127.0.0.1:12345
        String discover = serviceDiscovery.discover(rpcRequest.getClassName());

 客户端拉取的是ip地址+端口号,比如说俩个服务,zookeeper存储接口名和地址,

192.168.126.166:20880 和192.168.166.188:20880, 客户端选择一个ip地址就实现了负载均衡,这样客户端还还是向其中一个服务发送端口,服务的从Map<接口,实现类.Class>来get一个impl.整个思想就完成了

                                               atzhang

posted @ 2020-05-11 18:16  张艳涛&java  阅读(214)  评论(0编辑  收藏  举报