完整工程:https://download.csdn.net/download/haoranhaoshi/11268280
RPC(Remote Procedure Call,远程过程调用)核心代码:
package rpc;
/*
* Copyright 2011 Alibaba.com All right reserved. This software is the
* confidential and proprietary information of Alibaba.com ("Confidential
* Information"). You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement you entered
* into with Alibaba.com.
*/
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;
/**
* 服务端和客户端共享同一个接口,服务端进行接口的实现,客户端调用接口的方法。
* 靠Socket进行发送方法名,参数类型,参数值和接收,接收方法返回值。
* 可以多发送一个标志,如接口名称,靠接口名称对接接口的实现。
*/
public class RpcFramework {
/**
* 暴露服务
*
* @param service 服务实现
* @param port 服务端口
* @throws Exception
*/
public static void export(final Object service, int port) throws Exception {
if (service == null)
throw new IllegalArgumentException("service instance == null");
if (port <= 0 || port > 65535)
throw new IllegalArgumentException("Invalid port " + port);
System.out.println("Export service " + service.getClass().getName() + " on port " + port);
ServerSocket server = new ServerSocket(port);
for (; ; ) {
try {
final Socket socket = server.accept();
new Thread(new Runnable() {
@Override
public void run() {
try {
try {
// 服务端接收客户端的方法名,参数类型,参数值
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
try {
String methodName = input.readUTF();
Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
Object[] arguments = (Object[]) input.readObject();
// 服务端发送方法的返回值到客户端
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
try {
// 服务端执行客户端的方法
Method method = service.getClass().getMethod(methodName, parameterTypes);
Object result = method.invoke(service, arguments);
output.writeObject(result);
} catch (Throwable t) {
output.writeObject(t);
} finally {
output.close();
}
} finally {
input.close();
}
} finally {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 引用服务
*
* @param <T> 接口泛型
* @param interfaceClass 接口类型
* @param host 服务器主机名
* @param port 服务器端口
* @return 远程服务
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {
if (interfaceClass == null)
throw new IllegalArgumentException("Interface class == null");
if (!interfaceClass.isInterface())
throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");
if (host == null || host.length() == 0)
throw new IllegalArgumentException("Host == null!");
if (port <= 0 || port > 65535)
throw new IllegalArgumentException("Invalid port " + port);
System.out.println("Get remote service " + interfaceClass.getName() + " from server " + 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());
try {
output.writeUTF(method.getName());
output.writeObject(method.getParameterTypes());
output.writeObject(arguments);
// 客户端接收服务端方法的返回值
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
try {
Object result = input.readObject();
if (result instanceof Throwable) {
throw (Throwable) result;
}
return result;
} finally {
input.close();
}
} finally {
output.close();
}
} finally {
socket.close();
}
}
});
}
}
RMI(Remote Method Invocation,远程方法调用):
package rmi;
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
/**
* @Description:<p>服务端绑定</p>
*/
public class HelloServer {
HelloDefine hello;
public void server() throws RemoteException, MalformedURLException, AlreadyBoundException {
hello = new HelloDefineImp();
// 远程对象注册表实例
LocateRegistry.createRegistry(8888);
// 把远程对象注册到RMI注册服务器上
Naming.bind("rmi://localhost:8888/Hello", hello);
System.out.println("server:对象绑定成功!");
}
}
package rmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
/**
* 客户端调用
* RMI将RPC的底层进行了封装,是RPC面向对象的实现。
*/
public class HelloClient {
public HelloDefine hello;
public void client() throws MalformedURLException, RemoteException, NotBoundException {
// 在RMI注册表中查找指定对象。注册表即存根,得到的对象即代理。
hello = (HelloDefine) Naming.lookup("rmi://localhost:8888/Hello");
// 调用远程对象方法
System.out.println("client:");
System.out.println(hello.helloWorld());
System.out.println(hello.sayHello("风铃"));
}
}