简单RPC实现
2020-7-21 杨静
简单RPC实现','package com.howtd.rpc.rpc.demo;
public interface HelloService
{
String sysHello(String info);
}
package com.howtd.rpc.rpc.demo;
public class HelloServiceImpl implements HelloService
{
public String sysHello(String info)
{
return \"Hello word, \" + info;
}
}
package com.howtd.rpc.rpc.demo;
public class RpcConsumer
{
public static void main(String[] args) throws Exception
{
HelloService service = RpcHandle.refer(HelloService.class, \"127.0.0.1\", 8099);
for (int i = 0; i < 100 ; i ++)
{
String result = service.sysHello(\" \" + i);
System.out.println(result);
Thread.sleep(1000);
}
}
}
package com.howtd.rpc.rpc.demo;
public class RpcProvider
{
public static void main(String[] args) throws Exception
{
HelloService service = new HelloServiceImpl();
RpcHandle.export(service, 8099);
}
}
package com.howtd.rpc.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.ServerSocket;
import java.net.Socket;
@SuppressWarnings(\"unchecked\")
public class RpcHandle
{
public static void export(final Object service, int port) throws Exception
{
System.out.println(\"export service \" + service.getClass().getName() + \", port \" + port);
final ServerSocket server = new ServerSocket(port);
for(;;)
{
final Socket socket = server.accept();
new Thread(new Runnable()
{
public void run()
{
try
{
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
String methodName = input.readUTF();
Class<?>[] parameterTypes = (Class<?>[])input.readObject();
Object[] arguments = (Object[])input.readObject();
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
Method method = service.getClass().getMethod(methodName, parameterTypes);
Object result = method.invoke(service, arguments);
output.writeObject(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
public static <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception
{
System.out.println(\"refer service \" + interfaceClass.getName() + \" from \" + host + \":\" + port);
return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass},
new InvocationHandler()
{
public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable
{
Socket socket = new Socket(host, port);
try
{
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
output.writeUTF(method.getName());
output.writeObject(method.getParameterTypes());
output.writeObject(arguments);
System.out.println(\"################################## refer after output writeObject(); \");
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
Object result = input.readObject();
return result;
} finally {
socket.close();
}
}
});
}
}
发表评论: