根据设计生成两个接口,IRpcSend send方法返回数据要求包装成QResult对象
public interface IRpcSend { public <T> QResult<T> send(byte command, Object... args); }
public interface IRpcReceive { public <T> T receive(byte command, Objec[] args); }
public interface IRpcContext { RpcContext getContext(); void setContext(RpcContext ctx); }
public interface QResult<T> extends Future<T> { /** * 是否出错 * */ public boolean isError(); /** * 获取返回结果 * */ public T getResult(); /** * 设置结果 * */ public void setResult(T result); }
1 @SuppressWarnings("unchecked") 2 public abstract class QRpcFactory { 3 private static Method SEND_METHOD = ReflectUtil.getMethod(IRpcSend.class, "send"); 4 private static Method RECEIVE_METHOD = ReflectUtil.getMethod(IRpcReceive.class, "receive"); 5 6 private static Map<Short, Class<?>> SEND_CLASS = new HashMap<>(); 7 private static Map<Short, IRpcReceive> RECEIVE = new HashMap<>(); 8 9 public static <T> T loadSendProxy(Class<T> target, QNode... nodes) { 10 T ret = loadSendPorxy0(target); 11 IRpcContext ctx = (IRpcContext) ret; 12 ctx.setContext(RpcContext.of(nodes)); 13 return ret; 14 } 15 16 public static <T> T loadSendProxy(Class<T> target, Long... ids) { 17 T ret = loadSendPorxy0(target); 18 IRpcContext ctx = (IRpcContext) ret; 19 ctx.setContext(RpcContext.of(ids)); 20 return ret; 21 } 22 23 public static <T> T loadSendProxy(Class<T> target, String... addresses) { 24 T ret = loadSendPorxy0(target); 25 IRpcContext ctx = (IRpcContext) ret; 26 ctx.setContext(RpcContext.of(addresses)); 27 return ret; 28 } 29 30 private static <T> T loadSendPorxy0(Class<T> target) { 31 QModel modelAnno = ReflectUtil.getAnno(target, QModel.class); 32 Class<?> proxyClass = SEND_CLASS.get(modelAnno.value()); 33 T ret = null; 34 try { 35 ret = (T) proxyClass.newInstance(); 36 } catch (InstantiationException | IllegalAccessException e) { 37 throw new RuntimeException(e); 38 } 39 return ret; 40 } 41 42 public static <T> T loadLocalProxy(Class<T> target) { 43 QModel modelAnno = ReflectUtil.getAnno(target, QModel.class); 44 Object ret = RECEIVE.get(modelAnno.value()); 45 return (T) ret; 46 } 47 48 public static IRpcReceive loadReceiveProxy(short model) { 49 IRpcReceive ret = RECEIVE.get(model); 50 return ret; 51 } 52 }