protocol
{"namespace": "com.test.avro",
"protocol": "AvroTestInterface",
"types": [
{
"name":"typ",
"type":"enum",
"symbols":["remote", "local"]
},
{
"name": "SObj",
"type": "record",
"fields": [
{"name": "data", "type": "bytes"},
{"name": "styp", "type": "typ"}
]
}
],
// bool put(SObj req);
"messages": {
"put": { //method name
"request": [{"name": "req", "type": "SObj"}], // method parameters
"response": "boolean" // return type
}
}
}
java -jar avro-tools-1.7.5.jar compile protocol D:\...\protocol_test.avpr D:\...\src\main\java
server:
public class Server extends GenericResponder {
private Protocol protocol;
public Server(Protocol protocol, int port) {
super(protocol);
this.protocol = protocol;
}
@Override
public Object respond(Message message, Object request){
GenericRecord sObject = (GenericRecord) (((GenericRecord) request).get("req"));
EnumSymbol sObjTyp = (EnumSymbol) sObject.get("styp");
EnumSymbol styp2 = new GenericData.EnumSymbol(protocol.getType("typ"), "remote");
String key = sObject.get("key").toString();
ByteBuffer bb = (ByteBuffer) sObject.get("data");
byte[] datas = new byte[bb.capacity()];
bb.get(datas);
if (!sObjTyp.equals(styp2)) {
return false;
}
process(key, datas);
return true;
}
public static void main(String[] args) throws Exception {
int port = 10086;
Protocol p = Protocol.parse(new File("avpr file"));
HttpServer server = new HttpServer(new Server(p,port);
server.start();
}
}
client
public class Client {
private final String url = "http://localhost:10086";
private Protocol protocol;
public Client(Protocol protocol) {
this.protocol = protocol;
}
public void sendMessage() throws Exception {
ByteBuffer data; // get data
EnumSymbol styp = new GenericData.EnumSymbol(protocol.getType("typ"), "remote");
GenericRecord sObj = new GenericData.Record(protocol.getType("SObj"));
sObject.put("key", "key");
sObject.put("data", data);
sObject.put("styp", styp);
GenericRecord request = new GenericData.Record(protocol.getMessages().get("put").getRequest());
request.put("putReq", sObject);
Transceiver t = new HttpTransceiver(new URL(url));
GenericRequestor requestor = new GenericRequestor(protocol, t);
try {
Object o = requestor.request("put", request);
System.out.println("response=" + o);
} catch (Exception e) {
System.out.println(e.getMsg());
}
}
public static void main(String[] args) throws Exception {
Protocol p = Protocol.parse(new File("avpr file"));
Client client = newClient(p);
client.sendMessage();
}
}
idl
@namespace("com.test.avro")
protocol AvroTestInterface{
enum typ{
remote,
local
}
record SObj{
string key;
bytes data;
typ styp;
}
boolean put(SObject putReq);
}
java -jar avro-tools-1.7.5.jar idl D:\...\protocol_test.avdl D:\...\protocol_test.avpr