RPC即远程过程调用,被广泛使用,面向接口的编程。
consumer ———— provider
通过反射实现类的实例化
</pre></p><p>java代码如下:</p><p></p><p><h2>provider端</h2></p><p>接口类:<pre style="background-color:#c7edcc;color:#000000;font-family:'宋体';font-size:12.0pt;">SayHelloService
public interface SayHelloService { public String sayHello(String helloArg); }
接口实现类:SayHelloServiceImp
public class SayHelloServiceImp implements SayHelloService { public String sayHello(String helloArg) { if(helloArg.equals("good")){ return "good"; }else{ return "bad !!"; } }}
服务类:
ServerSocketTest
public class ServerSocketTest { private static ConcurrentHashMap<String,Object> services = new ConcurrentHashMap<String, Object>(10); static{ //类路径自己定义 services.put("com.jc.rpc.SayHelloService",new SayHelloServiceImp()); } public static void main(String[] args) { ServerSocket server = null; try { server = new ServerSocket(1234); while (true){ Socket socket = server.accept(); //读取服务信息 ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); String interfaceName = input.readUTF();//接口名称 String methodName = input.readUTF();//方法名称 Class<?>[] parameterTypes = (Class<?>[])input.readObject();//参数类型 Object[] arguments = (Object[])input.readObject();//参数对象 //执行调用 Class<?> serviceInterfaceClass = Class.forName(interfaceName); Object service = services.get(interfaceName);//取得服务实现的对象 Method method = serviceInterfaceClass.getMethod(methodName,parameterTypes); System.out.println("interface:"+interfaceName+",method:"+methodName+"arguments:"+ Arrays.toString(arguments)); Object result = method.invoke(service,arguments); ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); output.writeObject(result); } } catch (IOException e) { e.printStackTrace(); }catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
consumer端
客户端调用类:
public class SocketCilent { public static void main(String[] args) throws NoSuchMethodException, IOException, ClassNotFoundException { //接口名称 String interfaceName = SayHelloService.class.getName(); //需要传递到远端的参数 Object[] arguments = {"1"}; //需要远程执行的方法 Method method = SayHelloService.class.getMethod("sayHello", String.class); Socket socket = new Socket("127.0.0.1",8888); ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); output.writeUTF(interfaceName); output.writeUTF(method.getName()); output.writeObject(method.getParameterTypes()); output.writeObject(arguments); //从远端读取执行结果 ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); Object result = input.readObject(); System.out.println(result); } }
该方式采用的是阻塞式IO实现,下一篇会采用NIO方式实现,并且加入动态代理。