SayHelloService接口
public interface SayHelloService {
public String sayHello(String arg);
}
SayHelloServiceImpl实现类
public class SayHelloServiceImpl implements SayHelloService{
@Override
public String sayHello(String arg) {
return "Hello " + arg;
}
}
服务端 生产者
public class Provider {
public static void main(String[] args) {
try {
ServerSocket server= new ServerSocket(10808);
while (true) {
Socket socket = server.accept();
//读取服务信息
ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
String interfaceName = inputStream.readUTF();//接口名称
String methodName = inputStream.readUTF();//方法名称
Class<?>[] parameterTypes = (Class<?>[]) inputStream.readObject();//参数类型
Object[] parameters = (Object[]) inputStream.readObject();//参数对象
Class serviceInterfaceClass = Class.forName(interfaceName);
// Object service = services.get(interfaceName);
//服务端将事先实例化好的服务放在services这个Map中,通过interfaceName取出使用
Object service = new SayHelloServiceImpl();//演示代码直接new了一个对象来使用
//获取要调用的方法
Method method = serviceInterfaceClass.getMethod(methodName, parameterTypes);
Object result = method.invoke(service, parameters);
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
//将执行结果返回给调用端
outputStream.writeObject(result);
System.out.println("Parameters from comsumer: " + parameters);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭资源...
}
}
}
调用端 消费者
public class Consumer {
public static void main(String[] args) {
//接口名称
String interfaceName = SayHelloService.class.getName();
try {
//需要执行的远程方法
Method method = SayHelloService.class.getMethod("sayHello", java.lang.String.class);
//需要传递到远程端的参数
Object[] agrs = {"world"};
Socket socket = new Socket("127.0.0.1", 10808);
//将方法名称和参数传递到远端
ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.writeUTF(interfaceName);//接口名称
outputStream.writeUTF(method.getName());//方法名称
outputStream.writeObject(method.getParameterTypes());
outputStream.writeObject(agrs);
//从远端读取方法的执行结果
ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
Object result = inputStream.readObject();
System.out.println("Consumer result:" + result);
} catch (Exception e) {
e.printStackTrace();
}finally{
//关闭资源...
}
}
}
基于TCP协议实现的RPC,能灵活地对协议字段进行定制,减少网络传输字节数,降低网络开销,提高性能,实现更大的吞吐量和并发数。但是需要更多地关注底层复杂的细节,实现的代价更高,且由于所定义协议自身的局限性,难以得到平台厂商和开源社区的支持,较难实现跨平台的调用。
转载于:https://blog.51cto.com/shamrock/1743795