gRPC快速入门

gRPC 是一个高性能、开源和通用的 RPC 框架,面向移动和 HTTP/2 设计。目前提供 C、Java 和 Go 语言版本,分别是:grpc, grpc-java, grpc-go. 其中 C 版本支持 C, C++, Node.js, Python, Ruby, Objective-C, PHP 和 C# 支持.

gRPC 基于 HTTP/2 标准设计,带来诸如双向流、流控、头部压缩、单 TCP 连接上的多复用请求等特。这些特性使得其在移动设备上表现更好,更省电和节省空间占用。

研究gRPC之前,需要先熟悉Protocol Buffers

Protocol Buffers (ProtocolBuffer/ protobuf )是Google公司开发的一种数据描述语言,类似于XML能够将结构化数据序列化,可用于数据存储、通信协议等方面。现阶段支持C++、JAVA、Python等三种编程语言。

一:编写IDL文件 send_mail.proto

syntax = "proto3";

option java_multiple_files = true;
option java_package = "com.rpc.mail";
option java_outer_classname = "SendMailServiceProto";

message SendMailRequest {
	string recipient = 1;
    string title = 2;
    string content = 3;
}

message SendMailResponse {
	int32 code = 1;
	string msg = 2;
}

service SendMailService {
    rpc sendMail (SendMailRequest) returns (SendMailResponse) {}
}
这里定义了一个请求参数SendMailRequest,一个返回参数SendMailResponse,一个接口SendMailService

新建一个maven项目,把上面的proto文件放到src/main/proto目录

pom.xml里面增加如下配置

<dependencies>
	<dependency>
		<groupId>io.grpc</groupId>
		<artifactId>grpc-all</artifactId>
		<version>0.14.1</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.0.0-beta-2:exe:${os.detected.classifier}
				</protocArtifact>
				<pluginId>grpc-java</pluginId>
				<pluginArtifact>io.grpc:protoc-gen-grpc-java:0.14.1:exe:${os.detected.classifier}
				</pluginArtifact>
			</configuration>
			<executions>
				<execution>
					<goals>
						<goal>compile</goal>
						<goal>compile-custom</goal>
					</goals>
				</execution>
			</executions>
		</plugin>
	</plugins>
</build>
	

之后执行maven clean package即可生成java代码,生成的java代码在target\generated-sources\protobuf 目录

注意:插件里面的protobuf(protocArtifact、pluginArtifact)需要和grpc-core里面依赖的protobuf版本需要保持一致

二:编码

新建一个maven项目(也可以直接使用上一步创建的项目),在pom.xml里面加入如下配置

<dependencies>
	<dependency>
		<groupId>io.grpc</groupId>
		<artifactId>grpc-all</artifactId>
		<version>0.14.1</version>
	</dependency>
</dependencies>

然后把target\generated-sources\protobuf\java 和 target\generated-sources\protobuf\grpc-java 里面的代码放到src目录中去
目录结构如下:


接下来,写接口的实现类

package com.rpc.mail;

import io.grpc.stub.StreamObserver;

public class SendMailServiceImpl implements SendMailServiceGrpc.SendMailService {
	public void sendMail(SendMailRequest request, StreamObserver<SendMailResponse> responseObserver) {
		System.out.println(request.getRecipient() + "\t" + request.getTitle() + "\t" + request.getContent());
		//这里是具体的业务逻辑
		SendMailResponse resp = SendMailResponse.newBuilder().setCode(0).setMsg("OK").build();
		//设置返回结果
		responseObserver.onNext(resp);
		responseObserver.onCompleted();	
	}
}
服务端:

package com.rpc.mail;

import io.grpc.Server;
import io.grpc.netty.NettyServerBuilder;

public class GrpcServer {
	public static void main(String[] args) throws Exception {
		Server server = NettyServerBuilder.forPort(8080).addService(SendMailServiceGrpc.bindService(new SendMailServiceImpl())).build();
		server.start();
		System.out.println("server startup at 8080");
		server.awaitTermination();
	}
}
客户端:

package com.rpc.mail;

import java.util.concurrent.TimeUnit;
import com.rpc.mail.SendMailServiceGrpc.SendMailServiceBlockingStub;
import io.grpc.ManagedChannel;
import io.grpc.netty.NettyChannelBuilder;

public class GrpcClient {
	public static void main(String[] args) throws Exception {
		ManagedChannel channel = NettyChannelBuilder.forAddress("127.0.0.1", 8080).usePlaintext(true).build();
		//同步调用(异步调用的话,就是:SendMailServiceGrpc.newFutureStub(channel))
		SendMailServiceBlockingStub stub = SendMailServiceGrpc.newBlockingStub(channel);
		
		//设置请求参数
		SendMailRequest param = SendMailRequest.newBuilder().setRecipient("admin@google.com").setTitle("运维邮件").setContent("SOA服务挂了").build();
		SendMailResponse resp = stub.sendMail(param);
		System.out.println(resp.getMsg() + "\t" + resp.getCode());
		
		//close
		channel.shutdown().awaitTermination(1, TimeUnit.SECONDS);
	}
}
先启动服务端,之后,客户端就可以进行调用了。这样,一个简单的Grpc例子就做好了。






  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
gRPC 是一种高性能、开源的 RPC 框架,支持多种编程语言。在 Python 中,我们可以使用 gRPC 提供远程过程调用服务。 以下是在 Python 中使用 gRPC 的基本步骤: 1. 安装 gRPC:使用 pip install grpcio 命令安装 gRPC。 2. 定义服务和消息:使用 proto3 编写 .proto 文件,定义服务和消息。 3. 生成代码:使用 protoc 命令生成 Python 代码。 4. 实现服务:在 Python 中实现服务端和客户端。 5. 启动服务:启动服务端程序。 6. 调用服务:在客户端程序中调用远程服务。 以下是一个简单的示例,演示如何在 Python 中使用 gRPC: 1. 定义服务和消息 ```protobuf syntax = "proto3"; package helloworld; // 定义消息 message HelloRequest { string name = 1; } message HelloReply { string message = 1; } // 定义服务 service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } ``` 2. 生成代码 使用以下命令生成 Python 代码: ```bash python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. helloworld.proto ``` 3. 实现服务 在 Python 中实现服务端和客户端。 ```python import grpc import helloworld_pb2 import helloworld_pb2_grpc class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() server.wait_for_termination() if __name__ == '__main__': serve() ``` ```python import grpc import helloworld_pb2 import helloworld_pb2_grpc def run(): with grpc.insecure_channel('localhost:50051') as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name='world')) print("Greeter client received: " + response.message) if __name__ == '__main__': run() ``` 4. 启动服务 在终端中运行以下命令启动服务: ```bash python greeter_server.py ``` 5. 调用服务 在终端中运行以下命令调用服务: ```bash python greeter_client.py ``` 以上是在 Python 中使用 gRPC 的基本步骤。在生产环境中,我们需要考虑更多的实现细节,例如错误处理、认证和安全等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值