简单的RPC框架的实现

本文转载自阿里RPC框架DUBBO的作者粱老师的博客:http://javatar.iteye.com/blog/1123915

通过简单的几行代码就实现了一个RPC框架,对学习其他的RPC框架真的很有帮助。

package com.alibaba.study.rpc.framework;

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 RpcFramework {

	/**
	 * 暴露服务
	 * @param service 服务实现
	 * @param port 服务端口
	 * @throws Exception
	 */
	public static void export(final Object service, int port) throws Exception {
		if (service == null) {
			throw new IllegalAccessException("service install == null");
		}
		if (port <= 0 || port > 65535) {
			throw new IllegalAccessException("Invalid port " + port);
		}
		System.out.println("Export service " + service.getClass().getName() + " on port " + port);
		ServerSocket server = new ServerSocket(port);
		for (;;) {
			try {
				final Socket socket = server.accept();
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						ObjectInputStream input = null;
						ObjectOutputStream output = null;
						try {
							input = new ObjectInputStream(socket.getInputStream());
							String methodName = input.readUTF();
							Class<?>[] parameterTypes = (Class<?>[])input.readObject();
							Object[] arguments = (Object[])input.readObject();
							output = new ObjectOutputStream(socket.getOutputStream());
							Method method = service.getClass().getMethod(methodName, parameterTypes);
							Object result = method.invoke(service, arguments);
							output.writeObject(result);
						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							try {
								if (input != null) {
									input.close();
								}
								if (output != null) {
									output.close();
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
							
						}
					}
				}).start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	        /** 
		     * 引用服务 
		     *  
		     * @param <T> 接口泛型 
		     * @param interfaceClass 接口类型 
		     * @param host 服务器主机名 
		     * @param port 服务器端口 
		     * @return 远程服务 
		     * @throws Exception 
		     */
	@SuppressWarnings("unchecked")
	public static <T> T refer(final Class<T> interfaceClass, 
			final String host, final int port) throws Exception{
		if (interfaceClass == null) {
			throw new IllegalAccessException("Interface class == null");
		}
		if (!interfaceClass.isInterface()) {
			throw new IllegalAccessException("The " + interfaceClass.getName() + " must be interface class");
		}
		if (host == null || host.length() == 0) {
			throw new IllegalAccessException("Host == null");
		}
		if (port <= 0 || port > 65535) {
			throw new IllegalAccessException("Invalid port " + port);
		}
		System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":" + port);
		
		return (T)Proxy.newProxyInstance(interfaceClass.getClassLoader(), 
				new Class<?>[]{interfaceClass}, 
				new InvocationHandler() {
					
					@Override
					public Object invoke(Object proxy, Method method, Object[] args)
							throws Throwable {
						Object result = null;
						ObjectOutputStream output = null;
						ObjectInputStream input = null;
						try {
							Socket socket = new Socket(host, port);
							output = new ObjectOutputStream(socket.getOutputStream());
							output.writeUTF(method.getName());
							output.writeObject(method.getParameterTypes());
							output.writeObject(args);
							input = new ObjectInputStream(socket.getInputStream());
							result = input.readObject();
						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							try {
								if (input != null) {
									input.close();
								}
								if (output != null) {
									output.close();
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						return result;
					}
				});
	}
}

定义服务接口

package com.alibaba.study.rpc.test;

public interface HelloService {

	String hello(String name, int age);
}

实现服务

package com.alibaba.study.rpc.test;

public class HelloServiceImpl implements HelloService{

	@Override
	public String hello(String name, int age) {
		
		return "Hello " + name + ", age " + age;
	}

}

暴露服务

package com.alibaba.study.rpc.test;

import com.alibaba.study.rpc.framework.RpcFramework;

public class RpcProvider {

	public static void main(String[] args) throws Exception{
		HelloService service = new HelloServiceImpl();
		RpcFramework.export(service, 1234);
	}
}

引用服务

package com.alibaba.study.rpc.test;

import com.alibaba.study.rpc.framework.RpcFramework;

public class RpcConsumer {

	public static void main(String[] args) throws Exception{
		HelloService service = RpcFramework.refer(HelloService.class, "127.0.0.1", 1234);
		for (int i = 0; i < Integer.MAX_VALUE; i++) {
			String hello = service.hello("World" + i, i);
			System.out.println(hello);
			Thread.sleep(1000);
		}
	}
}

运行结果:


总结:

从这个小的Demo我们可以发现,RPC的精髓在于服务端所提供的动态代理,消费者通过接口去调用某个方法,其实最后是通过动态代理来调用到了服务端的真实方法,然而代理中参数,方法,接口的传递是通过TCP作为通讯方式实现而已,如果你有兴趣,还可以用Http进行实现。

2017-11-16补充:

上面的总结总感觉有问题,客户端在调用RPC服务时,客户端有调用服务的接口,而对接口的实现是在服务端进行的,服务端启动,监听某个接口,并将提供的服务(主要是地址+端口+服务)进行注册,你可以注册到内存也可以注册到zookeeper中间件,客户端调用类似于ClientProxy通过动态代理(这段代码是在客户端的),这段代码利用反射将客户端需要调用的服务(接口的字节码、参数、方法)组装成待发送的请求,然后通过网络工具(netty、jetty、mina、selvlet)的客户端经过序列化(Hessian、Jackson、Protostuff)发送到服务端,服务端接收到反序列化然后反射调用,OK

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值