1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| public class RpcProxy {
public static <T> T create(Class<?> clazz) { MethodProxy proxy = new MethodProxy(clazz); Class<?>[] interfaces = clazz.isInterface() ? new Class[]{clazz} : clazz.getInterfaces(); T result = (T) Proxy.newProxyInstance(clazz.getClassLoader(), interfaces, proxy); return result; }
public static class MethodProxy implements InvocationHandler { private Class<?> clazz;
public MethodProxy(Class<?> clazz) { this.clazz = clazz; }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); } else { return rpcInvoke(proxy, method, args); } }
private Object rpcInvoke(Object proxy, Method method, Object[] args) {
InvokerProtocol msg = new InvokerProtocol(); msg.setClassName(this.clazz.getName()); msg.setMethodName(method.getName()); msg.setParams(method.getParameterTypes()); msg.setValues(args); final RpcProxyHandler consumerHandler = new RpcProxyHandler(); EventLoopGroup group = new NioEventLoopGroup();
try { Bootstrap client = new Bootstrap(); client.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline();
int fieldLength = 4; pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, fieldLength, 0, fieldLength)); pipeline.addLast(new LengthFieldPrepender(fieldLength)); pipeline.addLast("encoder", new ObjectEncoder()); pipeline.addLast("decoder", new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
pipeline.addLast("handler", consumerHandler); } }) .option(ChannelOption.TCP_NODELAY, true);
ChannelFuture future = client.connect("localhost", 8080).sync(); future.channel().writeAndFlush(msg).sync(); future.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { group.shutdownGracefully(); }
return consumerHandler.getResponse(); } } }
|