你好开发!最近,我开始学习协议缓冲区和GRPC,Gotta告诉您,这项技术很棒!
这篇文章需要先验了解GRPC,Golang和Python
遵循这篇文章,以获取有关如何在使用GRPC上在不同代码库上运行的不同微服务之间建立通信的动手演示。
找到此帖子的代码here。
目录结构
fastapi-and-golang-grpc-demo
|-fastapi
|-app
|-env
|-requirements.txt
|-protobufs
|-auth.proto
|-main.go
|-Readme.md
|-go.mod
创建auth protobuf文件
在您喜欢的代码编辑器上打开auth.proto
文件,然后添加以下代码
syntax = "proto3";
package auth;
option go_package = "auth.utils/auth";
message AuthenticationRequest {
string token = 1;
}
message AuthenticationResponse {
int64 user_id = 1;
bool token_valid = 2;
}
service Auth {
rpc Authenticate (AuthenticationRequest) returns (AuthenticationResponse);
}
阅读有关协议缓冲区here的更多信息。
添加GO服务
1。用
初始化GO应用程序
$ go mod init auth-ms
2。生成GRPC代码
$ protoc --go_out=. --go-grpc_out=. protobufs/auth.proto
3。更新依赖关系
$ go mod tidy
4。让我们为Golang创建GRPC服务器,在main.go
文件中添加以下代码
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
pb "auth-ms/auth.utils/auth"
"google.golang.org/grpc"
)
var (
port = flag.Int("port", 50051, "port to run the server on")
)
type server struct {
pb.UnimplementedAuthServer
}
// extend the rpc service created in auth.proto
func (s *server) Authenticate(ctx context.Context, req *pb.AuthenticationRequest) (*pb.AuthenticationResponse, error) {
token := req.GetToken()
log.Printf("Received: %v", token)
// add some logic to verify token
return &pb.AuthenticationResponse{UserId: 1, TokenValid: true}, nil
}
func main() {
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil {
log.Fatalln("Unable to start the server on port", *port)
}
grpc_server := grpc.NewServer()
pb.RegisterAuthServer(grpc_server, &server{})
log.Println("Started server at", lis.Addr())
if err := grpc_server.Serve(lis); err != nil {
log.Fatalln("Failed to start server at", lis.Addr())
}
}
5。启动GRPC服务器并保持打开状态
$ go run main.go -port 8080
2022/11/06 16:26:39 Started server at [::]:8080
添加FastApi服务
1。安装依赖项
$ pip install fastapi uvicorn grpcio-tools~=1.30
2。生成GRPC代码
$ cd ./fastapi/app/
$ python -m grpc_tools.protoc -I ../protobufs --python_out=. --grpc_python_out=. ../protobufs/auth.proto
3。创建FastAPI服务器
from fastapi import FastAPI
import grpc
from compiled_pb.auth_pb2_grpc import AuthStub
from compiled_pb.auth_pb2 import AuthenticationRequest
app = FastAPI()
@app.get("/token/verify/")
def verify_token(token: str):
# gRPC client for making RPC calls to the server
channel = grpc.insecure_channel("localhost:8080")
client = AuthStub(channel)
request = AuthenticationRequest(token=token)
response = client.Authenticate(request)
data = {
"user_id": response.user_id,
"is_token_valid": response.token_valid
}
return data
4。启动fastapi sever
uvicorn main:app --host 127.0.0.1 --port 8000 --reload
INFO: Will watch for changes in these directories: ['/home/ankit/practice/golang_gRPC/fastapi/app']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [8652] using StatReload
INFO: Started server process [8654]
INFO: Waiting for application startup.
INFO: Application startup complete.
现在,转到http:127.0.0.1:8000/docs并击中/token/verify/
路线。
voilã,一旦您达到API请求,就会有一个内部RPC调用GO GRPC服务器。
快乐的编码!ðð