Avro Rpc

官方示例代码

协议定义

`{“namespace”: “example.proto”,
“protocol”: “Mail”,

“types”: [
{“name”: “Message”, “type”: “record”,
“fields”: [
{“name”: “to”, “type”: “string”},
{“name”: “from”, “type”: “string”},
{“name”: “body”, “type”: “string”}
]
}
],

“messages”: {
“send”: {
“request”: [{“name”: “message”, “type”: “Message”}],
“response”: “string”
}
}
}`
上述的协议相当于新定义了一种复杂数据类型,名字为Message,并且包含三个个属性to、from、body,类型皆为string。
messages在协议中包含特殊的含义,相当于曝露给外部可以调用的接口。如上面的协议,相当与包含了send的方法,方法入口参数为Message ,返回值为string。

Java 代码

定义一个类实现定义的协议,即实现send方法
public class Main {
public static class MailImpl implements Mail {
// in this simple example just return details of the message
public Utf8 send(Message message) {
System.out.println("Sending message");
return new Utf8("Sending message to " + message.getTo().toString()
+ " from " + message.getFrom().toString()
+ " with body " + message.getBody().toString());
}
}

下面在创建Responder时,会传入协议类,和实现类的示例,然后据此创建一个遵循该协议的Server。client端会创建一个符合协议类型的代理,通过代理来实现RPC功能。

private static Server server;
private static void startServer() throws IOException {
    server = new NettyServer(new SpecificResponder(Mail.class, new MailImpl()), new InetSocketAddress(65111));
    // the server implements the Mail protocol (MailImpl)
       }

public static void main(String[] args) throws IOException {
    if (args.length != 3) {
        System.out.println("Usage: <to> <from> <body>");
        System.exit(1);
    }

    System.out.println("Starting server");
    // usually this would be another app, but for simplicity
    //启动server
    startServer();
    System.out.println("Server started");

    NettyTransceiver client = new NettyTransceiver(new InetSocketAddress(65111));
    // client code - attach to the server and send a message
    Mail proxy = (Mail) SpecificRequestor.getClient(Mail.class, client);
    System.out.println("Client built, got proxy");

    // fill in the Message record and send it
    Message message = new Message();
    message.setTo(new Utf8(args[0]));
    message.setFrom(new Utf8(args[1]));
    message.setBody(new Utf8(args[2]));
    System.out.println("Calling proxy.send with message:  " + message.toString());
    System.out.println("Result: " + proxy.send(message));

    // cleanup
    client.close();
    server.close();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值