爱编程,爱生活程序员微服务

Rpc概述-实现一个简单的Rpc框架

2018-06-17  本文已影响42人  熬夜的猫头鹰

RPC,全称为Remote Procedure Call,即远程过程调用,它是一个计算机通信协议。它允许像调用本地服务一样调用远程服务。它可以有不同的实现方式。如RMI(远程方法调用)、Hessian、Http invoker等。另外,RPC是与语言无关的。

来张图:


RPC调用过程

如上图所示,假设Computer1在调用sayHi()方法,对于Computer1而言调用sayHi()方法就像调用本地方法一样,调用 –>返回。但从后续调用可以看出Computer1调用的是Computer2中的sayHi()方法,RPC屏蔽了底层的实现细节,让调用者无需关注网络通信,数据传输等细节。

好了,直接上代码:git地址 https://github.com/JeffySnail/simple-rpc

代码结构

API 代码:

package com.ibort.api;

/**
 * @author jeffy 
 * @date 2018-06-16
 */
public interface HelloService {

    /**
     * 定义一个API
     * @param name
     * @return
     */
    String sayHi(String name);
}

client 代码测试类

package com.ibort.client.main;

import com.ibort.api.HelloService;
import com.ibort.frame.server.RPCClient;

import java.net.InetSocketAddress;

/**
 * @author jeffy
 * @date 2018/6/16
 **/
public class Main {
    public static void main(String[] args) {
        HelloService service = RPCClient.getRemoteProxyObj(HelloService.class, new InetSocketAddress("localhost", 8088));
        System.out.println("客户端调用接口,返回结果为:" + service.sayHi("test"));
    }
}

rpc-frame 实现内部框架封装总共三个类

package com.ibort.frame.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.InetSocketAddress;
import java.net.Socket;

/**
 * @author jeffy
 * @date 2018/6/16
 **/
public class RPCClient<T> {
    public static <T> T getRemoteProxyObj(final Class<?> serviceInterface, final InetSocketAddress addr) {
        return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class<?>[]{serviceInterface}, new InvocationHandlerImp(addr, serviceInterface));

    }


    private static class InvocationHandlerImp implements InvocationHandler {

        private final InetSocketAddress addr;

        private Class<?> serviceInterface;

        public InvocationHandlerImp(InetSocketAddress addr, Class<?> serviceInterface) {
            this.addr = addr;
            this.serviceInterface = serviceInterface;
        }

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Socket socket = null;
            ObjectOutputStream output = null;
            ObjectInputStream input = null;
            try {
                // 2.创建Socket客户端,根据指定地址连接远程服务提供者
                socket = new Socket();
                socket.connect(addr);

                // 3.将远程服务调用所需的接口类、方法名、参数列表等编码后发送给服务提供者
                output = new ObjectOutputStream(socket.getOutputStream());
                output.writeUTF(serviceInterface.getName());
                output.writeUTF(method.getName());
                output.writeObject(method.getParameterTypes());
                output.writeObject(args);

                // 4.同步阻塞等待服务器返回应答,获取应答后返回
                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.ibort.frame.server;

import java.io.IOException;

/**
 * @author jeffy
 */
public interface Server {

    /**
     * 停止
     */
    void stop();

    /**
     * 启动
     *
     * @throws IOException
     */
    void start() throws IOException;

    /**
     * 注册服务
     *
     * @param serviceInterface
     * @param impl
     */
    void register(Class serviceInterface, Class impl);

    /**
     * 判断是否在运行
     *
     * @return
     */
    boolean isRunning();

    /**
     * 获取端口号
     *
     * @return
     */
    int getPort();

}
package com.ibort.frame.server;

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.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author jeffy
 * @date 2018/6/15
 **/
public class ServerCenter implements Server {
    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private static final HashMap<String, Class> serviceRegistry = new HashMap<String, Class>();
    private static boolean isRunning = false;
    private int port;


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

    public void stop() {
        isRunning = false;
        EXECUTOR_SERVICE.shutdown();
    }

    public void start() throws IOException {
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(port));
        try {
            while (true) {
                // 1.监听客户端的TCP连接,接到TCP连接后将其封装成task,由线程池执行
                EXECUTOR_SERVICE.execute(new ServiceTask(serverSocket.accept()));
            }
        } finally {
            serverSocket.close();
        }
    }

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

    public boolean isRunning() {
        return isRunning;
    }

    public int getPort() {
        return this.port;
    }

    private class ServiceTask implements Runnable {
        Socket client = null;

        public ServiceTask(Socket client) {
            this.client = client;
        }

        public void run() {
            ObjectInputStream input = null;
            ObjectOutputStream output = null;
            try {
                input = new ObjectInputStream(client.getInputStream());
                String serviceName = input.readUTF();
                String methodName = input.readUTF();
                Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
                Object[] arguments = (Object[]) input.readObject();
                Class serviceClass = serviceRegistry.get(serviceName);
                if (serviceClass == null) {
                    throw new ClassNotFoundException(serviceName + " not found");
                }
                Method method = serviceClass.getMethod(methodName, parameterTypes);
                Object result = method.invoke(serviceClass.newInstance(), arguments);
                output = new ObjectOutputStream(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 (client != null) {
                    try {
                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

server 模块包含两个类

package com.ibort.service;

import com.ibort.api.HelloService;

/**
 * @author jeffy
 * @date 2018/6/15
 **/
public class HelloServiceImpl implements HelloService {

    /**
     * 实现api定义的接口
     * @param name
     * @return
     */
    public String sayHi(String name) {
        System.out.println("收到客户端请求,参数为:  " + name);
        return "Hi, " + name;
    }
}
package com.ibort.main;

import com.ibort.api.HelloService;
import com.ibort.frame.server.Server;
import com.ibort.frame.server.ServerCenter;
import com.ibort.service.HelloServiceImpl;

import java.io.IOException;

/**
 * @author jeffy
 * @date 2018/6/17
 **/
public class Main {

    /**
     * start server
     * @param args
     */
    public static void main(String[] args) {
        Server serviceServer = new ServerCenter(8088);
        serviceServer.register(HelloService.class, HelloServiceImpl.class);
        try {
            System.err.println("server start");
            serviceServer.start();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

启动顺序

server start……
客户端调用接口,返回结果为:Hi, test

同时,在服务端看到控制台输出:

收到客户端请求,参数为:  test

至此,代码调试成功

这篇文章主要是对rpc原理的实现介绍,如果要实现一个rpc框架还有很多需要优化和考量的。这里实现的简单RPC框架是使用Java语言开发,与Java语言高度耦合,并且通信方式采用的Socket是基于BIO实现的,IO效率不高,还有Java原生的序列化机制占内存太多,运行效率也不高。可以考虑从下面几种方法改进。

目前主要流行的rpc款框架有阿里的dubbo 美团点评的pigeon,还有thrift等。

后边的文章会对pigeon进行源码解析。

参阅: https://www.cnblogs.com/codingexperience/p/5930752.html

上一篇下一篇

猜你喜欢

热点阅读