Golang微服务实战:使用gRPC实现跨语言通信! 随着微服务架构的发展,越来越多的企业开始采用微服务架构来构建分布式系统。在微服务架构中,服务之间的通信是非常重要的。而gRPC作为一种高效、跨平台、跨语言的RPC框架,成为越来越多企业的首选。 本篇文章将介绍如何使用gRPC实现跨语言通信。我们将实现一个用Golang编写的服务,与用Python编写的客户端通信,并探讨gRPC框架的一些核心技术点。
多个服务在进行拆分后,我们往往要通过服务之间互相调用来实现某个业务功能,我们知道在java领域,有springCloud,Dubbo这些封装的很好的通信组件,但是如果服务之间是跨语言的,那么这些就不能解决了,今天有个需求,我想实现go服务和java服务之间的通信,于是就借鉴了一下google的一个轻量且高效的通讯框架-grpc来实现
实现一个简单的,用Go服务远程调用Java服务一个整数相加的接口
- syntax = "proto3"; //协议版本号
-
- option java_multiple_files = true;
- option java_package = "io.grpc.add";
- option java_outer_classname = "remote_add_service";
-
- package Test; // 包名
-
- //定义服务
- service Greeter {
- //注意:这里是returns 不是return
- rpc RemoteAdd (AddRequest) returns (AddResponse) {}
- }
- //定义消息类型
- message AddRequest {
- int32 num1 = 1;
- int32 num2 = 2;
- }
- message AddResponse {
- int32 answer = 1;
- }
- protoc --go-grpc_out=. 你的proto文件名.proto
- protoc --go_out=. 你的proto文件名.proto
服务端启动java服务
客户端启动golang服务
client.go文件
- package main
-
- import (
- "fmt"
- "github.com/gin-gonic/gin"
- pb "go_grpc/pb"
- "google.golang.org/grpc"
- "log"
- "net/http"
- )
-
- func main() {
- // Set up a connection to the server.
- conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
- if err != nil {
- log.Fatalf("did not connect: %v", err)
- }
- defer conn.Close()
- client := pb.NewGreeterClient(conn)
-
- r := gin.Default()
- r.GET("/", func(c *gin.Context) {
- //todo 远程调用整数相加
- req := &pb.AddRequest{Num1: 10,Num2: 10}
- res, err := client.RemoteAdd(c, req)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": err.Error(),
- })
- return
- }
- c.JSON(http.StatusOK, gin.H{
- "result": fmt.Sprint(res.Answer),
- })
- })
- // Run http server
- if err := r.Run(":8052"); err != nil {
- log.Fatalf("could not run server: %v", err)
- }
- }
文件代码在我的git上,测试可以通过,大家可以fetch下来使用,里头的不同分支是不同的服务
https://github.com/zxhjames/grpc_demo