AVRO IPC HelloWorld

avro-ipc的HelloWorld例子
pom.xml
<dependency>
	<groupId>org.apache.avro</groupId>
	<artifactId>avro</artifactId>
</dependency>
<dependency>
	<groupId>org.apache.avro</groupId>
	<artifactId>avro-ipc</artifactId>
</dependency>
...
<plugin>
	<groupId>org.apache.avro</groupId>
	<artifactId>avro-maven-plugin</artifactId>
	<executions>
		<execution>
			<phase>generate-sources</phase>
			<goals>
				<goal>protocol</goal>
			</goals>
			<configuration>
				<sourceDirectory>${project.basedir}/src/main/avro/</sourceDirectory>
				<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
			</configuration>
		</execution>
	</executions>
</plugin>

helloworld.avpr
{
  "namespace": "com.sanss.hadoop.demos.avro.proto",
  "protocol": "HelloWorld",
  "doc": "Protocol Greetings",

  "types": [
    {"name": "Greeting", "type": "record", "fields": [
      {"name": "message", "type": "string"}]},
    {"name": "Curse", "type": "error", "fields": [
      {"name": "message", "type": "string"}]}
  ],

  "messages": {
    "hello": {
      "doc": "Say hello.",
      "request": [{"name": "greeting", "type": "Greeting" }],
      "response": "Greeting",
      "errors": ["Curse"]
    }
  }
}

生成java protocol code
mvn clean compile

HelloWorldImpl.java
public class HelloWorldImpl implements HelloWorld {

	@Override
	public Greeting hello(Greeting greeting) throws AvroRemoteException, Curse {
		if(greeting.getMessage().toString().equalsIgnoreCase("how are you")){
			greeting.setMessage("not too bad");
			return greeting;
		}
		return new Greeting("hello");
	}

}

IpcServer.java
public class IpcServer {
	private Server server;

	public void startServer() throws IOException, InterruptedException {
		server = new NettyServer(new SpecificResponder(HelloWorld.class,
				new HelloWorldImpl()), new InetSocketAddress(65000));
		
	}

	public void stopServer() {
		server.close();
	}

	public static void main(String[] args) throws IOException, InterruptedException {
		System.out.println("Starting server");
		IpcServer ipcServer = new IpcServer();
		ipcServer.startServer();
		System.out.println("Server started");
	}
}

Client.java
public class Client {

	public static void main(String[] args) throws IOException {
		NettyTransceiver client = new NettyTransceiver(new InetSocketAddress(65000));

		HelloWorld proxy = (HelloWorld) SpecificRequestor.getClient(HelloWorld.class, client);
        System.out.println("Client built, got proxy");
        
        Greeting greeting = new Greeting("how are you");
        System.out.println("Calling proxy.hello with message: " + greeting.toString());
        System.out.println("Result: " +proxy.hello(greeting));
        // cleanup
        client.close();
	}
}

运行结果
Client built, got proxy
Calling proxy.hello with message: {"message": "how are you"}
Result: {"message": "not too bad"}

猜你喜欢

转载自gqm.iteye.com/blog/1936110
IPC