1,接口定义

    public interface EchoService{
        String echo(String ping);
    }
    

     

    2,接口实现

    public Class EchoServiceImpl implements EchoService{
    
       @Override
       public String echo(String ping){
            return ping != null?ping + " -- > I am OK .":"I am Ok";
       }
    }

     

    3,RPC服务端服务发布者代码实现

    public class RpcExporter{
       static Executor executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    
       public static void exporter(String hostname,int port) throws Exception {
          ServerSocket server = new ServerSocket();
          server.bind(new InetSocketAddress(hostName,port));
          try{
             while(true){
               executor.execute(new ExporterTask(server.accept()));
             }
          }finally{
             server.close();
           }
       }
    }
    
    
    private static class ExporterTask implements Runnable{
    
       Socket client = null;
       public ExporterTask(Socket client){
         this.client = client;
       }
      @Override
      public ExporterTask(Socket client){
         this.client = client;
      }
    
      @Override
       public void run(){
         
    			ObjectInputStream input = null;
    			ObjectOutputStream output = null;
    			
    			try{
    				input = new ObjectInputStream(client.getInputStream());
    				String interfaceName = input.readUTF();
    				Class<?> service = Class.forName(interfaceName);
    				String methodName = input.readUTF();
    				Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
    				Object[] argments = (Object[]) input.readObject();
    				Method method = service.getMethod(methodName, parameterTypes);
    				Object result = method.invoke(service.newInstance(),argments);
    				output = new ObjectOutputStream(client.getOutputStream());
    				output.writeObject(result);
    				
    			}catch(Exception e){
    				e.printStackTrace();
    			}finally{
    				if(output !=null){
    					try {
    						output.close();
    					} catch (IOException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    				}
    				
    				if(input !=null){
    					try {
    						input.close();
    					} catch (IOException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    				}
    				
    				if(client!=null){
    					try {
    						client.close();
    					} catch (IOException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    				}
    			}
    		
      }
    }

     

    4,本地代理服务 RpcImporter

    public class RpcImporter<S> {
    
    	public S importer(final Class<?> serviceClass,final InetSocketAddress addr){
    		return (S) Proxy.newProxyInstance(serviceClass.getClassLoader(), new Class<?>[] {serviceClass.getInterfaces()[0]}, new InvocationHandler(){
    
    			@Override
    			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    				
    				Socket socket = null;
    				ObjectOutputStream output = null;
    				ObjectInputStream input = null;
    				try{
    					socket = new Socket();
    					socket.connect(addr);
    					output = new ObjectOutputStream(socket.getOutputStream());
    					output.writeUTF(serviceClass.getName());
    					output.writeUTF(method.getName());
    					output.writeObject(method.getParameterTypes());
    					output.writeObject(args);
    					input = new ObjectInputStream(socket.getInputStream());
    					return input.readObject();
    				}finally{
    					if(socket != null){
    						socket.close();
    					}
    					
    					if(output != null){
    						output.close();
    					}
    					
    					if(input != null ){
    						input.close();
    					}
    				}
    			}
    			
    		});
    	}
    }

     

    5, 测试代码 RpcTest

     

    public class RpcTest {
    
    	public static void main(String[] args) {
    		new Thread(new Runnable(){
    
    			@Override
    			public void run() {
    				try{
    					RpcExporter.exporter("localhost",8080);
    				}catch(Exception e){
    					e.printStackTrace();
    				}finally{
    					
    				}
    			}
    			
    		}).start();
    		
    		RpcImporter<EchoService> importer = new RpcImporter<EchoService>();
    		EchoService echo = importer.importer(EchoServiceImpl.class,new InetSocketAddress("localhost",8080));
    		System.out.println(echo.echo("Are you ok? "));
    	}
    }
    

     

    运行结果.

    Are you ok?  -- > I am Ok !

    联系QQ:343886028 --加QQ群 145315854