RPC demo

作者: mrjunwang | 来源:发表于2018-10-31 14:06 被阅读0次

    RPC Server端代码,主要是使用ServerSocket获得rpc调用客户端发送过来的类信息,方法信息及方法参数信息,通过反射在RPCServer端进行代码执行,最后将执行结果发送给Socket,第一步需要首先执行RPCServer。(转载 https://blog.csdn.net/qq924862077/article/details/52946580

    /**
     * @author jy
     * @date 2018年10月31日
     * <p>Description: </p> 
     */
    package rpc.demo;
    
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    import java.net.Socket;
    
    /**
     * @author jy
     *
     */
    public class RpcProxy {
    
        @SuppressWarnings("unchecked")
        public static <T> T create(final Object target)
        {
            return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler(){
    
                @Override
                public Object invoke(Object proxy, Method method, Object[] args)
                        throws Throwable {
    
                    Socket socket=new Socket("localhost",8080);
                    ObjectOutputStream output=new ObjectOutputStream(socket.getOutputStream());
                    output.writeUTF(target.getClass().getName());
                    output.writeUTF(method.getName());
                    output.writeObject(method.getParameterTypes());//参数类型
                    output.writeObject(args);//参数值
                    
                    ObjectInputStream input=new ObjectInputStream(socket.getInputStream());
                    
                    Object result=input.readObject();
                    if(result instanceof Throwable){
                        throw (Throwable)result;
                    }
                    input.close();
                    output.close();
                    socket.close();
                    return result;
                    
                    
                }
                
            });
        }
    }
    ···
    服务器端代码
    ```Java
    /**
     * @author jy
     * @date 2018年10月31日
     * <p>Description: </p> 
     */
    package rpc.demo;
    
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.concurrent.ConcurrentHashMap;
    
    /**
     * @author jy
     *
     */
    public class RpcServer {
        public static ConcurrentHashMap<String , Object> classMap=new ConcurrentHashMap<String, Object>();
        public static void invoker(int port) throws Exception{
            ServerSocket server=new ServerSocket(port);
            for(;;){
                try{
                    final Socket socket=server.accept();
                    new Thread(new Runnable(){
    
                        ObjectOutputStream out=null;
                        ObjectInputStream in=null;
                        @Override
                        public void run() {
    
                            try {
                                try {
                                out=new ObjectOutputStream(socket.getOutputStream());
                                in=new ObjectInputStream(socket.getInputStream());
                                String className=in.readUTF();
                                String methodName=in.readUTF();
                                Class<?>[] parameterType=(Class<?>[]) in.readObject();
                                Object[] arguments=(Object[]) in.readObject();
                                Object claszz=null;
                                if(!classMap.containsKey(className)){
                                    try {
                                        claszz=Class.forName(className).newInstance();
                                        classMap.put(className, claszz);
                                    } catch (InstantiationException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    } catch (IllegalAccessException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                                else{
                                    claszz=classMap.get(className);
                                }
                                
                                Method method=claszz.getClass().getMethod(methodName, parameterType);
                                Object result=method.invoke(claszz, arguments);
                                out.writeObject(result);
                                } catch (ClassNotFoundException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (SecurityException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (NoSuchMethodException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (IllegalArgumentException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (IllegalAccessException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (InvocationTargetException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }finally{
                                    out.close();
                                    in.close();
                                    
                                }
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            finally{
                                try {
                                    socket.close();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                            
                        }
                        
                    }).start();
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    
        public static void main(String args[]){
            RpcServer server=new RpcServer();
            try {
                server.invoker(8080);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    

    service

    public interface UserService {
        String getName(String userId);
        
        String addUser(String u);
    }
    

    impl

    /**
     * @author jy
     * @date 2018年5月4日
     * <p>Description: </p> 
     */
    package com.dubbo.service.impl;
    
    import org.springframework.stereotype.Component;
    
    
    @Component("userService")
    public class UserServiceImpl  implements UserService{
    
        /* (non-Javadoc)
         * @see com.dubbo.service.UserService#getName(java.lang.String)
         */
        @Override
        public String getName(String userId) {
            // TODO Auto-generated method stub
            return "userName"+userId;
        }
    
        /* (non-Javadoc)
         * @see com.dubbo.service.UserService#addUser(java.lang.String)
         */
        @Override
        public String addUser(String u) {
    
            System.out.println("add user");
            return null;
        }
    }
    

    main

    /**
     * @author jy
     * @date 2018年10月31日
     * <p>Description: </p> 
     */
    package socket.demo;
    
    import rpc.demo.RpcProxy;
    
    import com.dubbo.service.impl.UserService;
    import com.dubbo.service.impl.UserServiceImpl;
    
    /**
     * @author jy
     *
     */
    public class Main {
    
        /**
         * @param args
         *<p>Description: </p>  
         */
        public static void main(String[] args) {
    
            UserService userService = new UserServiceImpl();
            RpcProxy proxy=new RpcProxy();
            UserService userProxy=proxy.create(userService);
            System.out.println(userProxy.getName("jy"));
        }
    
    }
    

    相关文章

      网友评论

          本文标题:RPC demo

          本文链接:https://www.haomeiwen.com/subject/ztlatqtx.html