grpc是google在github于2015年开源的一款RPC框架,虽然protobuf很早google就开源了,但是google一直没推出正式的开源框架,导致github上基于protobuf的rpc五花八门,国内比较著名的有百度的sofa-pbrpc,但是遗憾的是soft-pbrpc没有对应的java实现版本。rgpc还有一个独立的官网:http://www.grpc.io/,目前已经支持的语言有 C, C++, Java, Go, Node.js, Python, Ruby, Objective-C, PHP 、 C#. grpc最大的特点是基于protobuf + http2 协议,http2协议虽然还未正式定稿,但从目前得知的内容来看,潜力巨大。下面是grpc基本的hello world的示例:
一、grpc-contract
还是按老套路,把服务涉及的对象定义、接口定义抽象出来,下面是项目结构图:
pom.xml的内容如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>yjmyzz.grpc</groupId> 8 <artifactId>grpc-contract</artifactId> 9 <version>1.0</version> 10 11 12 <dependencies> 13 14 <dependency> 15 <groupId>junit</groupId> 16 <artifactId>junit</artifactId> 17 <version>4.10</version> 18 </dependency> 19 20 <dependency> 21 <groupId>com.google.protobuf</groupId> 22 <artifactId>protobuf-java</artifactId> 23 <version>3.0.0-beta-1</version> 24 </dependency> 25 26 <dependency> 27 <groupId>io.grpc</groupId> 28 <artifactId>grpc-all</artifactId> 29 <version>0.8.0</version> 30 </dependency> 31 32 </dependencies> 33 34 <!--下面这个节点可选--> 35 <pluginRepositories> 36 <pluginRepository> 37 <releases> 38 <updatePolicy>never</updatePolicy> 39 </releases> 40 <snapshots> 41 <enabled>false</enabled> 42 </snapshots> 43 <id>central</id> 44 <name>Central Repository</name> 45 <url>https://repo.maven.apache.org/maven2</url> 46 </pluginRepository> 47 <pluginRepository> 48 <id>protoc-plugin</id> 49 <url>https://dl.bintray.com/sergei-ivanov/maven/</url> 50 </pluginRepository> 51 </pluginRepositories> 52 53 54 <build> 55 <extensions> 56 <extension> 57 <groupId>kr.motd.maven</groupId> 58 <artifactId>os-maven-plugin</artifactId> 59 <version>1.4.0.Final</version> 60 </extension> 61 </extensions> 62 <plugins> 63 <!--用于根据proto文件生成java类的插件--> 64 <plugin> 65 <groupId>com.google.protobuf.tools</groupId> 66 <artifactId>maven-protoc-plugin</artifactId> 67 <version>0.4.2</version> 68 <configuration> 69 <protocArtifact>com.google.protobuf:protoc:3.0.0-alpha-3.1:exe:${os.detected.classifier} 70 </protocArtifact> 71 <pluginId>grpc-java</pluginId> 72 <pluginArtifact>io.grpc:protoc-gen-grpc-java:0.8.0:exe:${os.detected.classifier}</pluginArtifact> 73 </configuration> 74 <executions> 75 <execution> 76 <goals> 77 <goal>compile</goal> 78 <goal>compile-custom</goal> 79 </goals> 80 </execution> 81 </executions> 82 </plugin> 83 84 <!--生成源代码jar包的插件(可选)--> 85 <plugin> 86 <artifactId>maven-source-plugin</artifactId> 87 <version>2.4</version> 88 <executions> 89 <execution> 90 <phase>package</phase> 91 <goals> 92 <goal>jar-no-fork</goal> 93 </goals> 94 </execution> 95 </executions> 96 </plugin> 97 98 </plugins> 99 </build> 100 </project>