`
young-2017
  • 浏览: 9442 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

rpc简单实现

    博客分类:
  • java
 
阅读更多
提供者:

public interface HelloService {

    String echo(String str);
}


public class HelloServiceImpl implements HelloService {

    public String echo(String str) {
        return "hello " + str;
    }
}

服务提供方通过反射调用:
package com.huayang.provider;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class RpcExporter {

    static Executor executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());


    public static void export(String hostName, int port) throws IOException {
        ServerSocket server = new ServerSocket();
        server.bind(new InetSocketAddress(hostName,port));
        try {
            while (true) {
                executor.execute(new ExportTask(server.accept()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


package com.huayang.provider;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

public class ExportTask implements Runnable {

    Socket client = null;

    public ExportTask(Socket client) {
        this.client = client;
    }

    public void run() {
        ObjectInputStream input = null;
        ObjectOutputStream output = null;
        try {
            input = new ObjectInputStream(client.getInputStream());

            String interfaceName = input.readUTF();
            System.out.println("pro" + interfaceName);
            Class<?> service = Class.forName(interfaceName);

            String methodName = input.readUTF();
            Class<?>[] paramsterTypes = (Class<?>[]) input.readObject();

            Object[] arguments = (Object[]) input.readObject();
            Method method = service.getMethod(methodName, paramsterTypes);
            Object result = method.invoke(service.newInstance(), arguments);
            output = new ObjectOutputStream(client.getOutputStream());
            output.writeObject(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != output) {
                    output.close();
                }
                if (null != input) {
                    input.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }
}





消费方:
通过动态代理实现:
package com.huayang.consumer;

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.InetSocketAddress;
import java.net.Socket;

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() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        Socket socket = null;
                        ObjectOutputStream output = null;
                        ObjectInputStream input = null;

                        socket = new Socket();
                        socket.connect(addr);
                        try {
                            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 (null != socket) {
                                socket.close();
                            }
                            if (null != output) {
                                output.close();
                            }
                            if (null != input) {
                                input.close();
                            }
                        }
                    }
                });
    }
}



测试类:
package com.huayang;

import com.huayang.consumer.RpcImporter;
import com.huayang.provider.HelloService;
import com.huayang.provider.RpcExporter;
import com.huayang.provider.impl.HelloServiceImpl;

import java.io.IOException;
import java.net.InetSocketAddress;

public class Test {


    public static void main(String[] args) {

        new Thread(new Runnable() {
            public void run() {
                try {
                    RpcExporter.export("localhost", 8080);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        RpcImporter<HelloService> importer = new RpcImporter<HelloService>();
        HelloService echo = importer.importer(HelloServiceImpl.class, new InetSocketAddress("localhost", 8080));
        System.out.println(echo.echo("young "));

    }


}





  • 大小: 232.1 KB
分享到:
评论
Global site tag (gtag.js) - Google Analytics