最近google发布了grpc1.0,数据交互使用了protocol buffer,相比之前使用的hession和json序列化方式性能应该提升不少,所有先搞一个grpc的hello world跑一下,项目使用maven搭建,并使用Eclipse开发。
一.使用Eclipse创建maven项目,添加pom配置
1.添加grpc1.0 maven依赖
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <grpc.version>1.4.0</grpc.version><!-- CURRENT_GRPC_VERSION --> </properties> <dependencies> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-netty</artifactId> <version>${grpc.version}</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-protobuf</artifactId> <version>${grpc.version}</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId> <version>${grpc.version}</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-testing</artifactId> <version>${grpc.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.9.5</version> <scope>test</scope> </dependency> </dependencies>
2.配置protobuf maven插件
配置了protobuf 插件后,可以自动将.proto文件生成对应的java代码。
<build> <extensions> <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> <version>1.4.1.Final</version> </extension> </extensions> <plugins> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.5.0</version> <configuration> <protocArtifact>com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier}</protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
配置完,整个pom.xml文件内容如下:
<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>com.bijian</groupId> <artifactId>test-grpc</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>test-grpc</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <grpc.version>1.4.0</grpc.version><!-- CURRENT_GRPC_VERSION --> </properties> <dependencies> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-netty</artifactId> <version>${grpc.version}</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-protobuf</artifactId> <version>${grpc.version}</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId> <version>${grpc.version}</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-testing</artifactId> <version>${grpc.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.9.5</version> <scope>test</scope> </dependency> </dependencies> <build> <extensions> <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> <version>1.4.1.Final</version> </extension> </extensions> <plugins> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.5.0</version> <configuration> <protocArtifact>com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier}</protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
二.编写proto文件helloworld.proto
syntax = "proto3"; option java_multiple_files = true; option java_package = "io.grpc.examples.helloworld"; option java_outer_classname = "HelloWorldProto"; option objc_class_prefix = "HLW"; package helloworld; // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1; }
然后点击pom.xml右击->Run as->Maven install,将会在target/generatedo-sources下生成的对应的java代码,如下所示:
将生成的代码拷贝到src/main/java下,如下所示(有几处@java.lang.Override的编译错误,去掉即可):
三.编写grpc 服务端HelloWorldServer.java
package com.bijian.test_grpc; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.examples.helloworld.GreeterGrpc; import io.grpc.examples.helloworld.HelloReply; import io.grpc.examples.helloworld.HelloRequest; import io.grpc.stub.StreamObserver; import java.io.IOException; public class HelloWorldServer { private int port = 50051; private Server server; private void start() throws IOException { server = ServerBuilder.forPort(port) .addService(new GreeterImpl()) .build() .start(); System.out.println("service start..."); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.err.println("*** shutting down gRPC server since JVM is shutting down"); HelloWorldServer.this.stop(); System.err.println("*** server shut down"); } }); } private void stop() { if (server != null) { server.shutdown(); } } // block 一直到退出程序 private void blockUntilShutdown() throws InterruptedException { if (server != null) { server.awaitTermination(); } } public static void main(String[] args) throws IOException, InterruptedException { final HelloWorldServer server = new HelloWorldServer(); server.start(); server.blockUntilShutdown(); } // 实现 定义一个实现服务接口的类 private class GreeterImpl extends GreeterGrpc.GreeterImplBase { public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) { System.out.println("service:"+req.getName()); HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } } }
四.编写grpc 客户端 HelloWorldClient.java
package com.bijian.test_grpc; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.examples.helloworld.GreeterGrpc; import io.grpc.examples.helloworld.HelloReply; import io.grpc.examples.helloworld.HelloRequest; import java.util.concurrent.TimeUnit; public class HelloWorldClient { private final ManagedChannel channel; private final GreeterGrpc.GreeterBlockingStub blockingStub; public HelloWorldClient(String host,int port){ channel = ManagedChannelBuilder.forAddress(host,port) .usePlaintext(true) .build(); blockingStub = GreeterGrpc.newBlockingStub(channel); } public void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } public void greet(String name){ HelloRequest request = HelloRequest.newBuilder().setName(name).build(); HelloReply response = blockingStub.sayHello(request); System.out.println(response.getMessage()); } public static void main(String[] args) throws InterruptedException { HelloWorldClient client = new HelloWorldClient("127.0.0.1",50051); for(int i=0;i<5;i++){ client.greet("world:"+i); } } }
五.项目完整结构
六.项目运行结果
服务端
service start... service:world:0 service:world:1 service:world:2 service:world:3 service:world:4 三月 17, 2018 9:30:40 下午 io.grpc.netty.NettyServerTransport notifyTerminated
客户端
Hello: world:0 Hello: world:1 Hello: world:2 Hello: world:3 Hello: world:4
参考文章:http://blog.csdn.net/whzhaochao/article/details/52421867
相关推荐
在这个"grpc java版本demo"中,我们将探讨如何使用 Java 实现 GRPC 的客户端和服务器。 1. **Protocol Buffers (protobuf)**: protobuf 是一种轻量级的数据序列化协议,用于结构化数据的编码和解码。它支持多种编程...
程序启动步骤1 启动服务端:运行 io/grpc/examples/helloworld/HelloWorldServer.java 的 main 方法2.启动客户端调用服务:运行:io/grpc/examples/helloworld/HelloWorldClient.java 的main 方法grpcThis guide ...
【标题】:“一个简单的gRPC开发demo” 在IT行业中,gRPC是一个高性能、开源和通用的RPC(远程过程调用)框架,它基于Google的Protocol Buffers(protobuf)进行序列化和接口定义。gRPC使用HTTP/2作为传输协议,...
这将生成`helloworld.pb.h`,`helloworld.pb.cc`,`helloworld_grpc.pb.h`和`helloworld_grpc.pb.cc`文件。 4. **创建VS2015项目**:使用CMake生成VS2015项目文件。在CMakeLists.txt中指定源文件和依赖库。 5. **...
5. Demo 测试:测试 Hello World Demo,以验证是否安装成功。 三、gRPC 的特性和应用场景 gRPC 的特性包括: * 高性能:gRPC 基于 HTTP/2 标准设计,带来了高性能的 RPC 框架。 * 双向流:gRPC 支持双向流,允许...
在Java中,常见的RPC框架有Hessian、RMI、gRPC、Dubbo和Spring Cloud等。 **服务提供者(Provider)**: 1. 定义接口:服务提供者首先需要定义一组服务接口,这些接口将被远程调用。接口通常放在独立的模块或jar...