avro

借鑑:https://www.iteye.com/blog/shift-alt-ctrl-2217425java

  1. springboot avro 父子maven pom.xmlweb

    父pomspring

    <?xml version="1.0" encoding="UTF-8"?>
    	<project xmlns="http://maven.apache.org/POM/4.0.0"
    			 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    			 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    		<modelVersion>4.0.0</modelVersion>
    
    		<groupId>tom.heliming.cloud</groupId>
    		<artifactId>cloud-demo</artifactId>
    		<packaging>pom</packaging>
    		<version>1.0-SNAPSHOT</version>
    		<modules>
    			<module>avro</module>
    		</modules>
    		<parent>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-parent</artifactId>
    			<version>1.5.9.RELEASE</version>
    			<relativePath/> <!-- lookup parent from repository -->
    		</parent>
    		<properties>
    			<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    			<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    			<maven.compiler.source>1.8</maven.compiler.source>
    			<maven.compiler.target>1.8</maven.compiler.target>
    			<java.version>1.8</java.version>
    		</properties>
    		<dependencies>
    
    			<!-- Spring Boot相關依賴 -->
    			<dependency>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-starter</artifactId>
    			</dependency>
    			<dependency>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-starter-web</artifactId>
    				<exclusions>
    					<exclusion>
    						<groupId>org.springframework.boot</groupId>
    						<artifactId>spring-boot-starter-tomcat</artifactId>
    					</exclusion>
    				</exclusions>
    			</dependency>
    			<!--war包方式-->
    			<dependency>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-starter-tomcat</artifactId>
    				<!--打包的時候能夠不用包進去,別的設施會提供。事實上該依賴理論上能夠參與編譯,測試,運行等週期。
    					至關於compile,可是打包階段作了exclude操做-->
    				<scope>provided</scope>
    			</dependency>
    		   <!-- 不加這個是由於加了這個只能加上tomcat之類的容器啓動不能用java -jar *.war啓動 -->
    			<!--<dependency>-->
    				<!--<groupId>javax.servlet</groupId>-->
    				<!--<artifactId>servlet-api</artifactId>-->
    				<!--<version>2.5</version>-->
    			<!--</dependency>-->
    			<!--<dependency>-->
    				<!--<groupId>org.springframework.boot</groupId>-->
    				<!--<artifactId>spring-boot-starter-jetty</artifactId>-->
    			<!--</dependency>-->
    
    			<dependency>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-starter-test</artifactId>
    				<!-- <scope>test</scope>-->
    			</dependency>
    
    
    		</dependencies>
    
    	</project>

    子pom文件apache

    <?xml version="1.0" encoding="UTF-8"?>
    	<project xmlns="http://maven.apache.org/POM/4.0.0"
    			 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    			 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    		<parent>
    			<artifactId>cloud-demo</artifactId>
    			<groupId>tom.heliming.cloud</groupId>
    			<version>1.0-SNAPSHOT</version>
    		</parent>
    		<modelVersion>4.0.0</modelVersion>
    
    		<packaging>war</packaging>
    
    		<groupId>tom.heliming.avro</groupId>
    		<artifactId>avro</artifactId>
    		<dependencies>
    			<dependency>
    				<groupId>org.apache.avro</groupId>
    				<artifactId>avro-ipc</artifactId>
    				<version>1.7.7</version>
    				<exclusions>
    					<exclusion>
    						<groupId>org.mortbay.jetty</groupId>
    						<artifactId>servlet-api</artifactId>
    					</exclusion>
    				</exclusions>
    			</dependency>
    			<dependency>
    				<groupId>org.apache.avro</groupId>
    				<artifactId>avro</artifactId>
    				<version>1.7.7</version>
    			</dependency>
    
    		</dependencies>
    
    		<build>
    			<!--<finalName>avroclient</finalName>-->
    			<!--<resources>-->
    			<!--&lt;!&ndash;表示把java目錄下的有關xml文件,properties文件編譯/打包的時候放在resource目錄下 &ndash;&gt;-->
    			<!--<resource>-->
    			<!--<directory>${basedir}/src/main/java</directory>-->
    			<!--<includes>-->
    			<!--<include>**/*.properties</include>-->
    			<!--<include>**/*.xml</include>-->
    			<!--</includes>-->
    			<!--</resource>-->
    			<!--<resource>-->
    			<!--<directory>${basedir}/src/main/resources</directory>-->
    			<!--</resource>-->
    			<!--</resources>-->
    			<!--<plugins>-->
    			<!--<plugin>-->
    			<!--<groupId>org.apache.maven.plugins</groupId>-->
    			<!--<artifactId>maven-compiler-plugin</artifactId>-->
    			<!--<version>2.3.2</version>-->
    			<!--<configuration>-->
    			<!--<target>1.8</target>-->
    			<!--<source>1.8</source>-->
    			<!--<encoding>UTF-8</encoding>-->
    			<!--</configuration>-->
    			<!--</plugin>-->
    			<!--<plugin>-->
    			<!--<groupId>org.apache.maven.plugins</groupId>-->
    			<!--<artifactId>maven-jar-plugin</artifactId>-->
    			<!--<configuration>-->
    			<!--<classesDirectory>target/classes/</classesDirectory>-->
    			<!--<archive>-->
    			<!--<manifest>-->
    			<!--&lt;!&ndash;<mainClass>top.util.Server</mainClass>&ndash;&gt;-->
    			<!--<mainClass>top.b</mainClass>-->
    			<!--<useUniqueVersions>false</useUniqueVersions>-->
    			<!--<addClasspath>true</addClasspath>-->
    			<!--<classpathPrefix>lib/</classpathPrefix>-->
    			<!--</manifest>-->
    			<!--<manifestEntries>-->
    			<!--<Class-Path>.</Class-Path>-->
    			<!--</manifestEntries>-->
    			<!--</archive>-->
    			<!--</configuration>-->
    			<!--</plugin>-->
    			<!--<plugin>-->
    			<!--<groupId>org.apache.maven.plugins</groupId>-->
    			<!--<artifactId>maven-dependency-plugin</artifactId>-->
    			<!--<executions>-->
    			<!--<execution>-->
    			<!--<id>copy-dependencies</id>-->
    			<!--<phase>package</phase>-->
    			<!--<goals>-->
    			<!--<goal>copy-dependencies</goal>-->
    			<!--</goals>-->
    			<!--<configuration>-->
    			<!--<type>jar</type>-->
    			<!--<includeTypes>jar</includeTypes>-->
    			<!--<outputDirectory>-->
    			<!--${project.build.directory}/lib-->
    			<!--</outputDirectory>-->
    			<!--</configuration>-->
    			<!--</execution>-->
    			<!--</executions>-->
    			<!--</plugin>-->
    
    			<!--</plugins>-->
    
    
    			<plugins>
    				<!-- avro 支持schema protocol idl-protocol 編譯打包 -->
    
    				<plugin>
    					<groupId>org.apache.avro</groupId>
    					<artifactId>avro-maven-plugin</artifactId>
    					<version>1.7.7</version>
    					<executions>
    						<execution>
    							<phase>generate-sources</phase>
    							<goals>
    								<goal>schema</goal>
    								<goal>protocol</goal>
    								<goal>idl-protocol</goal>
    							</goals>
    							<configuration>
    								<sourceDirectory>${project.basedir}/src/main/resources/avro/
    								</sourceDirectory>
    								<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
    							</configuration>
    						</execution>
    					</executions>
    				</plugin>
    				<!-- utf-8 編譯 -->
    				<plugin>
    					<groupId>org.apache.maven.plugins</groupId>
    					<artifactId>maven-compiler-plugin</artifactId>
    					<configuration>
    						<encoding>utf-8</encoding>
    					</configuration>
    				</plugin>
    				<!-- springboot 打包 -->
    				<plugin>
    					<groupId>org.springframework.boot</groupId>
    					<artifactId>spring-boot-maven-plugin</artifactId>
    					<executions>
    						<execution>
    							<goals>
    								<goal>repackage</goal>
    							</goals>
    						</execution>
    					</executions>
    					<configuration>
    						<includeSystemScope>true</includeSystemScope>
    					</configuration>
    				</plugin>
    			</plugins>
    
    		</build>
    	</project>

    application.ymljson

    server:
       port: 8081

    user.avsc放到一個地方寫測試test1 而後在resources的avro下放置寫test2,而後由於我配置了掃描resources下avro生成類因此在resources的avro下放置user.avsc執行 mvn compile 會生成java類 api

    user.avsctomcat

    {"namespace": "com.test.avro",
    	 "type": "record",
    	 "name": "User",
    	 "fields": [
    		 {"name": "name", "type": "string"},
    		 {"name": "age",  "type": ["int", "null"]},
    		 {"name": "email", "type": ["string", "null"]}
    	 ]
    	}

    resources的avro下放置helloworld.avpr執行 mvn compile 會生成java類 springboot

    helloworld.avprapp

    {
    	  "namespace": "com.test.avro.rpc",
    	  "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"]
    		}
    	  }
    	}

    而後本身寫實現dom

    package com.test.avro.rpc.impl;
    
    	import com.test.avro.rpc.Curse;
    	import com.test.avro.rpc.Greeting;
    	import com.test.avro.rpc.HelloWorld;
    
    	import org.apache.avro.AvroRemoteException;
    
    	/**
    	 * description: 本身寫的實現類
    	 *
    	 * @author: dawn.he QQ:       905845006
    	 * @email: dawn.he@cloudwise.com
    	 * @email: 905845006@qq.com
    	 * @date: 2019/9/10    8:40 PM
    	 */
    	public class HelloWorldImpl implements HelloWorld {
    
    		@Override
    		public Greeting hello(Greeting greeting) throws AvroRemoteException, Curse {
    			System.out.println(greeting.getMessage());
    			greeting.setMessage("From Server");
    			return greeting;
    		}
    	}

    執行test4();測試rpc調用

    Ceshi.java

    package top.util;
    
    	import com.test.avro.User;
    	import com.test.avro.rpc.Greeting;
    	import com.test.avro.rpc.HelloWorld;
    	import com.test.avro.rpc.impl.HelloWorldImpl;
    
    	import org.apache.avro.Schema;
    	import org.apache.avro.file.DataFileReader;
    	import org.apache.avro.file.DataFileWriter;
    	import org.apache.avro.generic.GenericData;
    	import org.apache.avro.generic.GenericDatumReader;
    	import org.apache.avro.generic.GenericDatumWriter;
    	import org.apache.avro.generic.GenericRecord;
    	import org.apache.avro.io.DatumReader;
    	import org.apache.avro.io.DatumWriter;
    	import org.apache.avro.ipc.NettyServer;
    	import org.apache.avro.ipc.NettyTransceiver;
    	import org.apache.avro.ipc.Server;
    	import org.apache.avro.ipc.specific.SpecificRequestor;
    	import org.apache.avro.ipc.specific.SpecificResponder;
    	import org.apache.avro.specific.SpecificDatumReader;
    	import org.apache.avro.specific.SpecificDatumWriter;
    
    	import java.io.File;
    	import java.io.IOException;
    	import java.io.InputStream;
    	import java.net.InetSocketAddress;
    
    
    	/**
    	 * description:
    	 *
    	 * @author: dawn.he QQ:       905845006
    	 * @email: dawn.he@cloudwise.com
    	 * @email: 905845006@qq.com
    	 * @date: 2019/9/10    6:58 PM
    	 */
    	public class Ceshi {
    
    		public static void main(String[] args) throws Exception {
    	//     test1();
    	//     test2();
    	//        test3();
    			test4();
    		}
    
    		public static void test1() throws IOException {
    			User.Builder builder = User.newBuilder();
    			builder.setName("張三");
    			builder.setAge(30);
    			builder.setEmail("zhangsan@*.com");
    			User user = builder.build();
    
    	//序列化
    			//寫本身的users.avro放置的目錄
    			File diskFile = new File("/Users/heliming/data/users.avro");
    			DatumWriter<User> userDatumWriter = new SpecificDatumWriter<User>(User.class);
    			DataFileWriter<User> dataFileWriter = new DataFileWriter<User>(userDatumWriter);
    	//指定schema
    			dataFileWriter.create(User.getClassSchema(), diskFile);
    			dataFileWriter.append(user);
    			dataFileWriter.fSync();//屢次寫入以後,能夠調用fsync將數據同步寫入磁盤(IO)通道
    			user.setName("李四");
    			user.setEmail("lisi@*.com");
    			dataFileWriter.append(user);
    			dataFileWriter.close();
    
    	//反序列化
    			DatumReader<User> userDatumReader = new SpecificDatumReader<User>(User.class);
    	// 也可使用DataFileStream
    	// DataFileStream<User> dataFileStream = new DataFileStream<User>(new FileInputStream(diskFile),userDatumReader);
    			DataFileReader<User> dataFileReader = new DataFileReader<User>(diskFile, userDatumReader);
    			User _current = null;
    			while (dataFileReader.hasNext()) {
    
    				//注意:avro爲了提高性能,_current對象只會被建立一次,且每次遍歷都會重用此對象
    				//next方法只是給_current對象的各個屬性賦值,而不是從新new。
    				_current = dataFileReader.next(_current);
    				//toString方法被重寫,將得到JSON格式
    				System.out.println(_current);
    			}
    			dataFileReader.close();
    		}
    
    
    	   public static void test2() throws IOException {
    			//user.avsc放置在「resources/avro」目錄下
    			InputStream inputStream = ClassLoader.getSystemResourceAsStream("avro/user.avsc");
    			Schema schema = new Schema.Parser().parse(inputStream);
    
    			GenericRecord user = new GenericData.Record(schema);
    			user.put("name", "張三");
    			user.put("age", 30);
    			user.put("email","zhangsan@*.com");
    
    			File diskFile = new File("/Users/heliming/data/users.avro");
    			DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
    			DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);
    			dataFileWriter.create(schema, diskFile);
    			dataFileWriter.append(user);
    			dataFileWriter.close();
    
    			DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema);
    			DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(diskFile, datumReader);
    			GenericRecord _current = null;
    			while (dataFileReader.hasNext()) {
    				_current = dataFileReader.next(_current);
    				System.out.println(user);
    			}
    
    			dataFileReader.close();
    		}
    
    
    		/**追加到末尾*/
    		public static void test3() throws IOException {
    			User.Builder builder = User.newBuilder();
    			builder.setName("張三");
    			builder.setAge(30);
    			builder.setEmail("zhangsan@*.com");
    			User user = builder.build();
    
    			File diskFile = new File("/Users/heliming/data/users.avro");
    			long length = diskFile.length();
    			DatumWriter<User> userDatumWriter = new SpecificDatumWriter<User>(User.class);
    			DataFileWriter<User> dataFileWriter = new DataFileWriter<User>(userDatumWriter);
    			if(length == 0) {
    				dataFileWriter.create(user.getClassSchema(), diskFile);//若是是新文件,則插入Schema
    
    			}else {
    				dataFileWriter.appendTo(diskFile);//對於現有文件,則直接追加到文件的尾部
    			}
    
    			dataFileWriter.append(user);
    			dataFileWriter.fSync();//屢次寫入以後,能夠調用fsync將數據同步寫入磁盤(IO)通道
    			user.setName("李四");
    			user.setEmail("lisi@*.com");
    			dataFileWriter.append(user);
    			dataFileWriter.close();
    
    	//反序列化
    			DatumReader<User> userDatumReader = new SpecificDatumReader<User>(User.class);
    	// 也可使用DataFileStream
    	// DataFileStream<User> dataFileStream = new DataFileStream<User>(new FileInputStream(diskFile),userDatumReader);
    			DataFileReader<User> dataFileReader = new DataFileReader<User>(diskFile, userDatumReader);
    			User _current = null;
    			while (dataFileReader.hasNext()) {
    
    				//注意:avro爲了提高性能,_current對象只會被建立一次,且每次遍歷都會重用此對象
    				//next方法只是給_current對象的各個屬性賦值,而不是從新new。
    				_current = dataFileReader.next(_current);
    				//toString方法被重寫,將得到JSON格式
    				System.out.println(_current);
    			}
    			dataFileReader.close();
    		}
    
    		private static void test4() throws Exception {
    			Server server = new NettyServer(new SpecificResponder(HelloWorld.class, new HelloWorldImpl()), new InetSocketAddress(9999));
    			server.start();
    			Thread.sleep(3000);
    
    			NettyTransceiver client = new NettyTransceiver(new InetSocketAddress(9999));
    			// client code - attach to the server and send a message
    			HelloWorld proxy = (HelloWorld) SpecificRequestor.getClient(HelloWorld.class, client);
    			Greeting request = new Greeting();
    			request.setMessage("From client");
    			Greeting response = proxy.hello(request);
    			System.out.println(response.getMessage());
    
    			client.close();
    			server.close();
    
    		}
    
    		//拆分的test4
    		public void server() throws InterruptedException {
    			String host = "localhost";
    			String port = "8088";
    			Server server = new NettyServer(new SpecificResponder(HelloWorld.class, new HelloWorldImpl()), new InetSocketAddress(host,Integer.valueOf(port)));
    			server.start();
    			server.join();
    		}
    		//拆分的test4
    		public void client() throws IOException {
    			String host = "localhost";
    			String port = "8088";
    			NettyTransceiver client = new NettyTransceiver( new InetSocketAddress(host,Integer.valueOf(port)));
    			// client code - attach to the server and send a message
    			HelloWorld proxy = (HelloWorld) SpecificRequestor.getClient(HelloWorld.class, client);
    			Greeting request = new Greeting();
    			request.setMessage("From client");
    			Greeting response = proxy.hello(request);
    			System.out.println(response.getMessage());
    		}
    	}

    http測試

    MyThreadClass.java

    package top.service;
    
    	/**
    	 * description:
    	 *
    	 * @author: dawn.he QQ:       905845006
    	 * @email: dawn.he@cloudwise.com
    	 * @email: 905845006@qq.com
    	 * @date: 2019/9/10    3:34 PM
    	 */
    	import java.util.concurrent.Callable;
    	/**
    	 * @Author 笑笑
    	 * @Date 18:37 2018/05/23
    	 */
    	public class MyThreadClass implements Callable<Object>{
    
    		//V call()  因爲該方法的返回值是個泛型V,因此具體的返回類型能夠本身定義,下面返回值設置爲了String,
    		@Override
    		public Object call() throws Exception {
    
    			Object o = new Object();
    			o = "笑笑";
    			return o;
    		}
    	}

    a.avro 模板

    {
    		"namespace":"avro",
    		"doc":"This is a message.",
    		"protocol":"messageProtocol",
    		"name":"HelloWorld",
    		"types":[
    			{
    				"name":"nameMessage",
    				"type":"record",
    				"fields":[ {"name":"name", "type":"string"} ]
    			}
    		],
    		"messages":{
    			"sayHello":{
    				"doc":"say Hello to manbers",
    				"request":[ { "name":"name", "type":"string" } ],
    				"response":"nameMessage"
    			}
    		}
    	}

    AvroHttpServer.java

    package top;
    
    	/**
    	 * description:
    	 *
    	 * @author: dawn.he QQ:       905845006
    	 * @email: dawn.he@cloudwise.com
    	 * @email: 905845006@qq.com
    	 * @date: 2019/9/9    2:48 PM
    	 */
    
    	import com.test.avro.rpc.HelloWorld;
    	import com.test.avro.rpc.impl.HelloWorldImpl;
    
    	import java.io.File;
    	import java.net.InetSocketAddress;
    
    	import org.apache.avro.Protocol;
    	import org.apache.avro.Protocol.Message;
    	import org.apache.avro.generic.GenericData;
    	import org.apache.avro.generic.GenericRecord;
    	import org.apache.avro.ipc.HttpServer;
    	import org.apache.avro.ipc.NettyServer;
    	import org.apache.avro.ipc.Server;
    	import org.apache.avro.ipc.generic.GenericResponder;
    	import org.apache.avro.ipc.specific.SpecificResponder;
    	import org.apache.commons.logging.Log;
    	import org.apache.commons.logging.LogFactory;
    
    	public class AvroHttpServer extends GenericResponder {
    
    		private static Log log = LogFactory.getLog(AvroHttpServer.class);
    
    		public AvroHttpServer(Protocol protocol) {
    			super(protocol);
    		}
    
    		public Object respond(Message message, Object request) throws Exception {
    			GenericRecord req = (GenericRecord) request;
    			GenericRecord reMessage = null;
    			if (message.getName().equals("sayHello")) {
    				Object name = req.get("name");
    				//  do something...
    				//取得返回值的類型
    				reMessage = new GenericData.Record(super.getLocal().getType("nameMessage"));
    				//直接構造回覆
    				reMessage.put("name", "HelloController, " + name.toString());
    				log.info(reMessage);
    			}
    			return reMessage;
    		}
    
    
    		public void server() {
    			int port = 8088;
    			try {
    				//1. http
    				Server server = new HttpServer(
    						new AvroHttpServer(Protocol.parse(
    	//                            new File("helloword.json"))),
    								//寫你的a.avro放置的位置
    
    								new File("/Users/heliming/IdeaProjects/democloud/avro/src/main/resources/avro/a.avro"))),
    						port);
    
    				server.start();
    				server.join();
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    
    		public static void main(String[] args) throws Exception {
    			new AvroHttpServer(Protocol.parse(
    	//                            new File("helloword.json"))),
    					//寫你的a.avro放置的位置
    
    					new File("/Users/heliming/IdeaProjects/democloud/avro/src/main/resources/avro/a.avro"))).server();
    		}
    
    
    	}

    AvroRpcRequestor.java

    package top;
    
    	/**
    	 * description:
    	 *
    	 * @author: dawn.he QQ:       905845006
    	 * @email: dawn.he@cloudwise.com
    	 * @email: 905845006@qq.com
    	 * @date: 2019/9/10    2:34 PM
    	 */
    
    	import com.test.avro.rpc.Greeting;
    	import com.test.avro.rpc.HelloWorld;
    
    	import org.apache.avro.Protocol;
    	import org.apache.avro.generic.GenericData;
    	import org.apache.avro.generic.GenericRecord;
    	import org.apache.avro.ipc.HttpTransceiver;
    	import org.apache.avro.ipc.NettyTransceiver;
    	import org.apache.avro.ipc.Transceiver;
    	import org.apache.avro.ipc.generic.GenericRequestor;
    	import org.apache.avro.ipc.specific.SpecificRequestor;
    	import org.apache.commons.logging.Log;
    	import org.apache.commons.logging.LogFactory;
    
    	import java.io.File;
    	import java.io.IOException;
    	import java.net.InetSocketAddress;
    	import java.net.URL;
    	import java.text.SimpleDateFormat;
    	import java.util.Date;
    	import java.util.UUID;
    	import java.util.concurrent.ExecutionException;
    	import java.util.concurrent.ExecutorService;
    	import java.util.concurrent.Executors;
    	import java.util.concurrent.Future;
    	import java.util.concurrent.TimeUnit;
    	import java.util.concurrent.TimeoutException;
    
    	import top.service.MyThreadClass;
    
    	public class AvroRpcRequestor {
    		private static final Log logger = LogFactory.getLog(AvroRpcRequestor.class);
    
    		private static final SimpleDateFormat dateFormate = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
    		private static final int EXECUTE_NUM = 1;
    		private ExecutorService executor = Executors.newCachedThreadPool();
    
    
    		public static void main(String[] args) throws Exception {
    			System.out.println(String.format("aa%s", new Object[]{Integer.valueOf(1)}));
    			new AvroRpcRequestor().request();
    		}
    
    		public Object request() throws Exception {
    			String host = "localhost";
    			String port = "8088";
    			String messageName = "nameMessage";
    			final String requestId = dateFormate.format(new Date()).concat(UUID.randomUUID().toString());
    			logger.info(String.format("request start , id is [%s]", new Object[]{requestId}));
    
    			Future future = this.executor.submit(new MyThreadClass() {
    
    				public Object call() throws Exception {
    					Transceiver transceiver = null;
    					try {
    
    						//1. http
    						//寫你的a.avro放置的位置
    	//                    Protocol protocol = Protocol.parse(new File("/Users/heliming/IdeaProjects/democloud/avro/src/main/resources/avro/a.avro"));
    	//                    Transceiver t = new HttpTransceiver(new URL("http://localhost:8088"));  //這裏若是要在兩臺機器上運行記得把localhost改爲服務端的ip
    	//                    GenericRequestor requestor = new GenericRequestor(protocol, t);
    	//                    // initiate the request data
    	//                    GenericRecord requestData = new GenericData.Record(protocol.getType("nameMessage"));
    	//                    requestData.put("name", "zhenqin");
    	//                    System.out.println(requestData);
    	//                    Object result = requestor.request("sayHello", requestData);
    	//                    if (result instanceof GenericData.Record) {
    	//                        GenericData.Record record = (GenericData.Record) result;
    	//                        System.out.println(record.get("name"));
    	//                    }
    	//                    System.out.println(result);
    
    						//2. netty
    						NettyTransceiver client = new NettyTransceiver(new InetSocketAddress(host, Integer.valueOf(port)));
    						// client code - attach to the server and send a message
    						HelloWorld proxy = (HelloWorld) SpecificRequestor.getClient(HelloWorld.class, client);
    						Greeting request = new Greeting();
    						request.setMessage("From client");
    						Greeting response = proxy.hello(request);
    						Object result = response.getMessage();
    						System.out.println(response.getMessage());
    						return result;
    					} catch (IOException ioe) {
    						AvroRpcRequestor.logger.error(String.format("===========================future call error, id is [%s]", new Object[]{requestId}), ioe);
    						throw ioe;
    					} finally {
    						if (transceiver != null)
    							transceiver.close();
    					}
    				}
    			});
    			try {
    				return future.get(60L, TimeUnit.SECONDS);
    			} catch (ExecutionException exe) {
    				future.cancel(true);
    				logger.error(String.format("request [%s:%s] execution error======%s, id is [%s]", new Object[]{host, Integer.valueOf(port), messageName, requestId}), exe.getCause());
    
    				throw exe;
    			} catch (InterruptedException ie) {
    				Thread.interrupted();
    				future.cancel(true);
    				logger.error(String.format("request [%s:%s] interrupted======%s, id is [%s]", new Object[]{host, Integer.valueOf(port), messageName, requestId}), ie);
    
    				throw ie;
    			} catch (TimeoutException te) {
    				future.cancel(true);
    				logger.error(String.format("request [%s:%s] timeout======%s, id is [%s]", new Object[]{host, Integer.valueOf(port), messageName, requestId}), te);
    
    				throw te;
    			}
    		}
    
    	}

    HelloController.java

    package top.Controller;
    
    	import org.springframework.beans.factory.annotation.Autowired;
    	import org.springframework.web.bind.annotation.GetMapping;
    	import org.springframework.web.bind.annotation.RequestMapping;
    	import org.springframework.web.bind.annotation.RestController;
    
    	import top.AvroRpcRequestor;
    	import top.util.Ceshi;
    
    	/**
    	 * description:
    	 *
    	 * @author: dawn.he QQ:       905845006
    	 * @email: dawn.he@cloudwise.com
    	 * @email: 905845006@qq.com
    	 * @date: 2019/9/10    3:04 PM
    	 */
    	@RestController
    	@RequestMapping("/avro")
    	public class HelloController {
    
    
    		@GetMapping("/all")
    		public String hello() throws Exception {
    			new AvroRpcRequestor().request();
    
    			return "success:avro";
    		}
    
    		@GetMapping("/server")
    		public String server() throws Exception {
    			new Ceshi().server();
    
    			return "success:avroserver";
    		}
    
    		@GetMapping("/fqq")
    		public String fqq() throws Exception {
    			return "success:avroserver";
    		}
    	}

    AcroApp.java 啓動類

    package top;
    
    	import org.apache.avro.Protocol;
    	import org.springframework.boot.SpringApplication;
    	import org.springframework.boot.autoconfigure.SpringBootApplication;
    	import org.springframework.boot.builder.SpringApplicationBuilder;
    	import org.springframework.boot.web.support.SpringBootServletInitializer;
    
    	import java.io.File;
    	import java.io.IOException;
    
    	import top.util.Ceshi;
    
    	/**
    	 * description:
    	 *
    	 * @author: dawn.he QQ:       905845006
    	 * @email: dawn.he@cloudwise.com
    	 * @email: 905845006@qq.com
    	 * @date: 2019/9/10    3:03 PM
    	 */
    	@SpringBootApplication
    	//public class AcroApp {
    	public class AcroApp extends SpringBootServletInitializer {
    		public static void main(String[] args) throws IOException, InterruptedException {
    			SpringApplication.run(AcroApp.class, args);
    			//http
    	//        new AvroHttpServer(Protocol.parse(
    	////                            new File("helloword.json"))),
    			//寫你的a.avro放置的位置
    	//                new File("/Users/heliming/IdeaProjects/democloud/avro/src/main/resources/avro/a.avro"))).server();
    
    			//netty
    			new Ceshi().server();
    		}
    
    		//打war包的時候,由於我resources下沒有靜態頁面我不重寫這個了
    	//        @Override
    	//        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    	//            return builder.sources(AcroApp.class);
    	//        }
    	}
    1. 若是不用web項目直接測試main函數就行。

    2. 若是是web項目打jar包把子pom文件的 <packaging>war</packaging>去掉啓動類不要繼承SpringBootServletInitializer 訪問:http://localhost:8081/avro/all就行

    3. 啓動war包直接java -jar xxx.war也能啓動不過得訪問下http://localhost:8081/avro/server 而後訪問http://localhost:8081/avro/all

    4. 若是是用tomcat之類的容器啓動得訪問下 http://localhost:8080/avro/server 而後訪問http://localhost:8080/avro/all

    解釋:用war包訪問server一直沒有響應不要緊我接口中用到thread.join方法了把線程的控制權讓出去了因此沒有響應,須要的本身改下就行。

相關文章
相關標籤/搜索