关于grpc的定义,就不叙述了,因为百度上面太多了。
但还是要说一句:gRPC是一个高性能、开源和通用的RPC(远程过程调用协议)框架
现在上代码,就是一个简单的列子,仿照官网和一些博客上面
开发工具:IDEA,maven构建
项目结构,proto,java这两个文件夹当成空的来看
1:maven文件配置:
三个重要的jar包
<?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>com.ming</groupId><artifactId>grpc_demo</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><name>grpc_demo Maven Webapp</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><grpc.version>1.0.3</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></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.1.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><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.6</source><target>1.6</target></configuration></plugin></plugins></build>
</project>
2:我们在proto文件夹下创建一个hello.proto
// 指定格式
syntax = "proto3";//一些生成代码的设置
option java_multiple_files = true;
option java_package = "com.ming.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";package helloworld;// 定义了一个 service
service Greeter {// 发送一个greetingrpc SayHello (HelloRequest) returns (HelloReply) {}
}// 定义一个消息请求体
message HelloRequest {string name = 1;
}// 定义一个消息回复体
message HelloReply {string message = 1;
}
3:生成代码
然后我们就会发现这个
现在我们开始编写服务端和客户端的代码:
客户端:HelloWorldClient.java
import com.ming.helloworld.HelloReply;
import com.ming.helloworld.HelloRequest;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import com.ming.helloworld.GreeterGrpc;import java.util.Scanner;
import java.util.concurrent.TimeUnit;/*** 客户端* @author MING* @date 2018/10/28 2:38*/
public class HelloWorldClient {private final ManagedChannel channel; //一个gRPC信道private final GreeterGrpc.GreeterBlockingStub blockingStub;//阻塞/同步 存根//初始化信道和存根public HelloWorldClient(String host,int port){this(ManagedChannelBuilder.forAddress(host, port)// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid// needing certificates..usePlaintext(true));}/** Construct client for accessing RouteGuide server using the existing channel. */private HelloWorldClient(ManagedChannelBuilder<?> channelBuilder) {channel = channelBuilder.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;try {response = blockingStub.sayHello(request);} catch (StatusRuntimeException e) {System.out.println("RPC调用失败:"+e.getMessage());return;}System.out.println("服务器返回信息:"+response.getMessage());}public static void main(String[] args) throws InterruptedException {HelloWorldClient client = new HelloWorldClient("127.0.0.1",50051);try {Scanner sc = new Scanner(System.in);String next = sc.next();client.greet("world:"+next);}finally {client.shutdown();}}
}
服务端:HelloWorldServer.java
import com.ming.helloworld.GreeterGrpc;
import com.ming.helloworld.HelloReply;
import com.ming.helloworld.HelloRequest;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;import java.io.IOException;/*** 服务端* @author MING* @date 2018/10/28 2:36*/
public class HelloWorldServer {private int port = 50051;private Server server;/*** 启动服务* @throws IOException*/private void start() throws IOException {server = ServerBuilder.forPort(port).addService(new GreeterImpl()).build().start();System.out.println("service start...");Runtime.getRuntime().addShutdownHook(new Thread() {@Overridepublic 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("收到的信息:"+req.getName());//这里可以放置具体业务处理代码 start//这里可以放置具体业务处理代码 end//构造返回HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build();responseObserver.onNext(reply);responseObserver.onCompleted();}}
}
最后项目结构:
然后运行看下效果:先运行服务端
IDEA 需要下载支持proto的插件
总体感觉起来,不是太难,但是现在就会发现一个问题,就是基于这个小demo为什么跑成功了?
https://www.jianshu.com/p/46d600e5a1b1这篇文章中就会有详细的说明
转自:https://www.jianshu.com/p/46d600e5a1b1