avro - Remote Procedure Call (RPC)

RPC-remote procedure call, that is, the method of locally calling objects on the machine on the other end of the network. I have previously contacted remote services through httpclient, jsonpon, etc. Both methods require an application server container, such as tomcat, to run remote services. RPC calls are like calling native methods, without the help of the container.

RPC

HTTP

AVRO-RPC is implemented based on NIO's NETTY network communication framework. The usage steps are as follows:

write avdl file

@namespace("com.jv.avro")
protocol AddService{
import schema "user.avsc";
int add(int x , int y);
void parseUser(com.jv.avro.User user);
}

namespace: namespace

protocol: declares AddService as a protocol

    import: import schema files, you can also import avpr, avdl files

    int add(int x, int y): defined method

generate code

Test code:

Server

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{

	@Override
	public int add(int x, int y) throws AvroRemoteException {
		return x+y;
	}

	@Override
	public Void parseUser(User user) throws AvroRemoteException {
		System.out.println(user);
		return null;
	}
}

client

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);
	}
}

Server input:

Client output:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326474545&siteId=291194637