简单实现RPC(02)
程序员文章站
2022-06-01 21:32:34
...
接口和实现类
package cm.zhangjinhe.server;
public interface helloService {
String sayHello(String str);
}
package cm.zhangjinhe.server;
public class helloServiceImpl implements helloService{
@Override
public String sayHello(String str) {
return "hello world " + str;
}
}
服务接口和实现类
package cm.zhangjinhe.provider;
import java.io.IOException;
public interface Provider {
public void stop();
public void start() throws IOException;
public void register(Class serviceInterface, Class impl);
public boolean isRunning();
public int getPort();
}
package cm.zhangjinhe.provider;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ProviderImpl implements Provider{
private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private static final HashMap<String, Class> serviceRegistry = new HashMap<String, Class>();
private static boolean isRunning = false;
private static int port;
public ProviderImpl(int port){
this.port = port;
}
@Override
public void stop() {
isRunning = false;
executor.shutdown();
}
@Override
public void start() throws IOException {
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(port));
System.out.println("---start server---");
try {
while (true){
executor.execute(new ServiceTask(serverSocket.accept()));
}
}catch (Exception e){
e.printStackTrace();
}finally {
serverSocket.close();
}
}
@Override
public void register(Class serviceInterface, Class impl) {
serviceRegistry.put(serviceInterface.getName(), impl);
}
@Override
public boolean isRunning() {
return isRunning;
}
@Override
public int getPort() {
return port;
}
private static class ServiceTask implements Runnable{
Socket client = null;
public ServiceTask(Socket client){
this.client = client;
}
@Override
public void run() {
ObjectInputStream input = null;
ObjectOutputStream output = null;
try {
input = new ObjectInputStream(client.getInputStream());
String serviceName = input.readUTF();
String methodName = input.readUTF();
Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
Object[] arguments = (Object[]) input.readObject();
Class serviceClass = serviceRegistry.get(serviceName);
if (serviceClass == null) {
throw new ClassNotFoundException(serviceName + " not found");
}
Method method = serviceClass.getMethod(methodName, parameterTypes);
Object result = method.invoke(serviceClass.newInstance(), arguments);
output = new ObjectOutputStream(client.getOutputStream());
output.writeObject(result);
} catch (Exception e){
e.printStackTrace();
} finally {
if(output != null){
try {
output.close();
}catch (Exception e1){
e1.printStackTrace();
}
}
if(input != null){
try {
input.close();
} catch (Exception e2){
e2.printStackTrace();
}
}
if(client != null){
try {
client.close();
}catch (Exception e3){
e3.printStackTrace();
}
}
}
}
}
}
调用类
package cm.zhangjinhe.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 Consumer {
public static <T> T getRemoteProxyObj(final Class<?> serviceInterface, final InetSocketAddress addr) {
// 1.将本地的接口调用转换成JDK的动态代理,在动态代理中实现接口的远程调用
return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class<?>[] { serviceInterface },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Socket socket = null;
ObjectOutputStream output = null;
ObjectInputStream input = null;
try {
// 2.创建Socket客户端,根据指定地址连接远程服务提供者
socket = new Socket();
socket.connect(addr);
// 3.将远程服务调用所需的接口类、方法名、参数列表等编码后发送给服务提供者
output = new ObjectOutputStream(socket.getOutputStream());
output.writeUTF(serviceInterface.getName());
output.writeUTF(method.getName());
output.writeObject(method.getParameterTypes());
output.writeObject(args);
// 4.同步阻塞等待服务器返回应答,获取应答后返回
input = new ObjectInputStream(socket.getInputStream());
return input.readObject();
} finally {
if (socket != null)
socket.close();
if (output != null)
output.close();
if (input != null)
input.close();
}
}
});
}
}
测试类
package cm.zhangjinhe.Test;
import cm.zhangjinhe.consumer.Consumer;
import cm.zhangjinhe.provider.ProviderImpl;
import cm.zhangjinhe.provider.Provider;
import cm.zhangjinhe.server.*;
import com.sun.corba.se.spi.activation.Server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
public class RPCTest {
public static void main(String[] args) throws IOException {
new Thread(new Runnable() {
@Override
public void run() {
try {
Provider provider = new ProviderImpl(8088);
provider.register(helloService.class, helloServiceImpl.class);
provider.start();
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
helloService service = Consumer.getRemoteProxyObj(helloService.class, new InetSocketAddress("127.0.0.1", 8088));
System.out.println(service.sayHello("zhangjinhe"));
}
}