Avro实现RPC

场景:一个客户端,一个服务端(创建两个avro工程)。客户端向服务端发送数据,服务端根据算法算出结果,返回给客户端。

Http主外,RPC主内。(解决分布式环境下,节点间的数据通信或远程过程调用

实现步骤

1.创建两个maven工程

2.引入pom文件

3.更改maven工程结构(src/main/avro)

4.创建模式文件(协议文件)

5.根据avro插件生成文件对应的接口类

6.利用API实现rpc

具体实现

1、 创建两个maven项目,修改jdk版本和编译的版本  1.5->1.7

2、 拷贝pom.xml文件

3、 创建资源文件夹src/main/avro

4、 创建模式文件(协议文件),在客户端项目和服务器端项目都要有一份协议文件。

@namespace("rpc.service")

protocol AddService{

int add(int x,int y);

}

5、 选择项目右键->Run->Maven generate-sources

6、 在服务器端的项目中添加一个实现类

public class AddServiceImpl implements AddService {

public int add(int x, int y) throws AvroRemoteException {

return x+y;

}

}

7、 在服务器端项目中,开发Server

package cn.tedu.avro_server;

import java.net.InetSocketAddress;

import org.apache.avro.ipc.NettyServer;

import org.apache.avro.ipc.specific.SpecificResponder;

import rpc.service.AddService;

import rpc.service.AddServiceImpl;

public class Server {

public static void main(String[] args) {

NettyServer server = new NettyServer(

new SpecificResponder(AddService.class,

new AddServiceImpl()),

new InetSocketAddress(6666));

}

}

8、 在客户端项目中开发Client

public class Client {

public static void main(String[] args) throws Exception {

//指定rpc服务器端的ip地址和端口号

Transceiver transciever = new NettyTransceiver(

new InetSocketAddress("127.0.0.1", 6666));

//获取rpc服务器端接口实现类的对象

AddService proxy = SpecificRequestor.getClient(

AddService.class, transciever);

//调用对象的方法

int result = proxy.add(3, 5);

System.out.println(result);

}

}

原文地址:https://www.cnblogs.com/sxpy-lj/p/7482047.html