2019独角兽企业重金招聘Python工程师标准>>>
RPC-远程过程调用,即本地调用网络另一端机器上对象的方法,以前接触过通过httpclient,jsonpon等方式调用远程服务,这两种方式都需要一个应用服务器容器,比如tomcat来运行远程的服务。RPC调用就像调用本地方法一样,不需要容器来帮忙。
RPC
HTTP
AVRO-RPC是基于NIO的NETTY网络通信框架实现的,使用步骤:
编写avdl文件
@namespace("com.jv.avro")
protocol AddService{
import schema "user.avsc";
int add(int x , int y);
void parseUser(com.jv.avro.User user);
}
namespace:命名空间
protocol:声明AddService为一个协议
import:导入模式文件,还可以导入avpr,avdl文件
int add(int x,int y):定义的方法
生成代码
测试代码:
服务端
package com.jv.test;import java.net.InetSocketAddress;import org.apache.avro.AvroRemoteException;
import org.apache.avro.ipc.NettyServer;
import org.apache.avro.ipc.specific.SpecificResponder;import com.jv.avro.AddService;
import com.jv.avro.User;public class TestRPCServer {public static void main(String[] args) {NettyServer ns = new NettyServer(new SpecificResponder(AddService.class,new ServerImpl()),new InetSocketAddress(9999));//ns.start();System.out.println("服务端已启动");}}class ServerImpl implements AddService{@Overridepublic int add(int x, int y) throws AvroRemoteException {return x+y;}@Overridepublic Void parseUser(User user) throws AvroRemoteException {System.out.println(user);return null;}
}
客户端
package com.jv.test;import java.io.IOException;
import java.net.InetSocketAddress;import org.apache.avro.ipc.NettyTransceiver;
import org.apache.avro.ipc.specific.SpecificRequestor;import com.jv.avro.AddService;
import com.jv.avro.User;public class TestRPCClient {public static void main(String[] args) throws IOException {NettyTransceiver client = new NettyTransceiver(new InetSocketAddress("127.0.0.1",9999));AddService proxy = SpecificRequestor.getClient(AddService.class, client);int result = proxy.add(2, 3);System.out.println("客户端接收到结果:" + result);User user = new User("Messi",30,"巴塞罗那");proxy.parseUser(user);}
}
服务端输入:
客户端输出: