Skip to content

Instantly share code, notes, and snippets.

@mtth
Created February 26, 2016 15:45
Show Gist options
  • Save mtth/e94e3bb95671143d7251 to your computer and use it in GitHub Desktop.
Save mtth/e94e3bb95671143d7251 to your computer and use it in GitHub Desktop.
Avro RPC

Sample JavaScript client and Java server RPC setup.

/* jshint node: true */
'use strict';
var avro = require('avsc'),
http = require('http');
// Parse protocol file.
var protocol = avro.parse('./mail.avpr');
var message = protocol.getType('example.proto.Message');
// HTTP emitter, assuming the server is listening on localhost:8888.
var ee = protocol.createEmitter(function (cb) {
return http.request({
port: 8888,
headers: {'content-type': 'avro/binary'},
method: 'POST'
}).on('response', function (res) { cb(res); });
});
// Send a sample message, and print the response to stdout.
protocol.emit('send', {message: message.random()}, ee, function (err, res) {
if (err) {
console.error(err);
return;
}
console.log('response: ' + res);
});
{
"protocol": "Mail",
"namespace": "example.proto",
"doc": "From https://github.com/phunt/avro-rpc-quickstart/blob/master/src/main/avro/mail.avpr",
"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"
}
}
}
import example.proto.Mail; // This example assumes the protocol has been compiled.
import example.proto.Message;
import java.io.IOException;
import org.apache.avro.ipc.HttpServer;
import org.apache.avro.ipc.HttpTransceiver;
import org.apache.avro.ipc.specific.SpecificResponder;
import org.apache.avro.util.Utf8;
public class Server {
public static class MailImpl implements Mail {
// Echo each message back.
public Utf8 send(Message message) {
return new Utf8(
"Got message to " + message.getTo().toString() +
" from " + message.getFrom().toString() +
" with body " + message.getBody().toString()
);
}
}
public static void main(String[] args) throws IOException {
HttpServer server = new HttpServer(new SpecificResponder(Mail.class, new MailImpl()), 8888);
server.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment