接第01部分,本节用来说明Java语言的代码实现。
使用avro生成java代码之后,会生成两个java文件,无论是Client还是Server都要包含这两个文件。
首先是Server端:
1、新建一个java项目,引用以下jar包
avro-1.8.0.jar
avro-ipc-1.8.0.jar
jackson-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar
netty-3.5.13.Final.jar
slf4j-api-1.7.7.jar
slf4j-simple-1.7.7.jar
2、项目中添加生成的两个java文件。
3、新建一个类MyAvroServer,实现JustATest接口
package com.neohope.avro.test; import org.apache.avro.AvroRemoteException; public class MyAvroServer implements JustATest{ @Override public CharSequence SayHelloTo(Person person) throws AvroRemoteException { return "Hello "+person.getName(); } @Override public int Add(int a, int b) throws AvroRemoteException { return a+b; } }
4、修改TestServer.java
package com.neohope.avro.test; import org.apache.avro.ipc.NettyServer; import org.apache.avro.ipc.specific.SpecificResponder; import java.net.InetSocketAddress; import java.util.Scanner; public class TestServer { public static void main(String[] args) { NettyServer server = new NettyServer(new SpecificResponder( JustATest.class, new MyAvroServer()), new InetSocketAddress(1900)); server.start(); Scanner sc=new Scanner(System.in); sc.nextLine(); server.close(); } }
5、编译运行
然后是Client端:
1、新建一个java项目,引用以下jar包
avro-1.8.0.jar
avro-ipc-1.8.0.jar
jackson-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar
netty-3.5.13.Final.jar
slf4j-api-1.7.7.jar
slf4j-simple-1.7.7.jar
2、项目中添加生成的两个java文件。
3、修改TestClient.java
package com.neohope.avro.test; import org.apache.avro.AvroRemoteException; import org.apache.avro.ipc.NettyTransceiver; import org.apache.avro.ipc.specific.SpecificRequestor; import org.apache.avro.util.Utf8; import java.io.IOException; import java.net.InetSocketAddress; public class TestClient { public static void main(String[] args) throws IOException { NettyTransceiver client = new NettyTransceiver(new InetSocketAddress("localhost",1900)); JustATest proxy = (JustATest) SpecificRequestor.getClient(JustATest.class, client); Person person = new Person(); person.setSex(new Utf8("male")); person.setName(new Utf8("neohope")); person.setAddress(new Utf8("shanghai")); System.out.println(proxy.SayHelloTo(person)); System.out.println(proxy.Add(1,2)); client.close(); } }
4、编译运行