|
| 1 | +package org.jee.rpc; |
| 2 | + |
| 3 | +import java.io.ObjectInputStream; |
| 4 | +import java.io.ObjectOutputStream; |
| 5 | +import java.lang.reflect.InvocationHandler; |
| 6 | +import java.lang.reflect.Method; |
| 7 | +import java.lang.reflect.Proxy; |
| 8 | +import java.net.InetSocketAddress; |
| 9 | +import java.net.Socket; |
| 10 | + |
| 11 | +/** |
| 12 | + * 描述:Rpc本地服务代理类 |
| 13 | + * 1. 将本地接口调用转化为JDK的动态调用,在动态调用中实现接口的远程调用 |
| 14 | + * 2. 创建Socket客户端,根据制定地址连接远程服务提供者 |
| 15 | + * 3. 将远程服务调用所需的接口类,方法名,参数列表等编码后发送给服务提供者 |
| 16 | + * 4. 同步阻塞等待服务端返回应答,获取应答后返回 |
| 17 | + * Created by bysocket on 16/2/29. |
| 18 | + */ |
| 19 | +public class RpcImporter<S> { |
| 20 | + public S importer(final Class<?> serviceClass, final InetSocketAddress address) { |
| 21 | + // JDK动态代理,实现接口的远程调用 |
| 22 | + return (S) Proxy.newProxyInstance(serviceClass.getClassLoader(), |
| 23 | + new Class<?>[]{serviceClass.getInterfaces()[0]}, |
| 24 | + new InvocationHandler() { |
| 25 | + |
| 26 | + @Override |
| 27 | + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { |
| 28 | + Socket socket = null; |
| 29 | + ObjectOutputStream output = null; |
| 30 | + ObjectInputStream input = null; |
| 31 | + |
| 32 | + try { |
| 33 | + // 连接远程服务提供者 |
| 34 | + socket = new Socket(); |
| 35 | + socket.connect(address); |
| 36 | + |
| 37 | + // 对象输出流 |
| 38 | + output = new ObjectOutputStream(socket.getOutputStream()); |
| 39 | + output.writeUTF(serviceClass.getName()); |
| 40 | + output.writeUTF(method.getName()); |
| 41 | + output.writeObject(method.getParameterTypes()); |
| 42 | + output.writeObject(args); |
| 43 | + |
| 44 | + input = new ObjectInputStream(socket.getInputStream()); |
| 45 | + return input.readObject(); |
| 46 | + } finally { |
| 47 | + if (socket != null) { |
| 48 | + socket.close(); |
| 49 | + } |
| 50 | + if (output != null) { |
| 51 | + output.close(); |
| 52 | + } |
| 53 | + if (input != null) { |
| 54 | + input.close(); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + }); |
| 59 | + } |
| 60 | +} |
0 commit comments