在php小編魚仔的幫助下,我們來探究一下grpc中的api是如何實(shí)現(xiàn)的。gRPC是一個高性能、開源的遠(yuǎn)程過程調(diào)用(RPC)框架,它使用了Google的Protocol Buffers作為接口描述語言,并支持多種編程語言。gRPC的核心機(jī)制是基于HTTP/2協(xié)議,通過序列化和反序列化消息來實(shí)現(xiàn)客戶端和服務(wù)器之間的通信。在本文中,我們將深入了解gRPC的工作原理、消息傳遞方式以及如何使用它來構(gòu)建強(qiáng)大的分布式應(yīng)用程序。讓我們開始吧!
問題內(nèi)容
我使用了官方文檔https://grpc.io/docs/languages/go/basics/,但是實(shí)現(xiàn)后,出現(xiàn)了問題。
當(dāng)我創(chuàng)建 tcp 服務(wù)器時,我必須指定主機(jī)和端口(在我的例子中為 mcrsrv-book:7561)。
但是如果我想為 grpc 實(shí)現(xiàn)另一個 api 該怎么辦?我是否需要在新端口上啟動另一臺服務(wù)器(例如 mcrsrv-book:7562)?
grpc中的路由和api是如何實(shí)現(xiàn)的?
我的服務(wù)器代碼是:
type routeGuideServer struct {
pb.UnimplementedRouteGuideServer
savedFeatures []*pb.Response // read-only after initialized
}
// GetFeature returns the feature at the given point.
func (s *routeGuideServer) GetFeature(ctx context.Context, request *pb.Request) (*pb.Response, error) {
context := localContext.LocalContext{}
book := bookRepository.FindOrFailBook(context, int(request.BookId))
return &pb.Response{
Name: book.Name,
BookId: int32(book.BookId),
AuthorId: int32(book.AuthorId),
Category: book.Category,
Description: "Описание",
}, nil
}
func newServer() *routeGuideServer {
s := &routeGuideServer{}
return s
}
func SomeAction() {
lis, err := net.Listen("tcp", fmt.Sprintf("mcrsrv-book:7561"))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
var opts []grpc.ServerOption
grpcServer := grpc.NewServer(opts...)
pb.RegisterRouteGuideServer(grpcServer, newServer())
grpcServer.Serve(lis)
}
登錄后復(fù)制
我認(rèn)為除了為每個 grpc 服務(wù)打開單獨(dú)的端口之外,還應(yīng)該有其他選擇。
grpc中的api是如何實(shí)現(xiàn)的?
解決方法
如果您想將同一地址用于不同的服務(wù),只需在啟動 grpc 服務(wù)器之前重新注冊其他服務(wù)即可。
grpcServer := grpc.NewServer(opts...) pb.RegisterRouteGuideServer(grpcServer, newServer()) #register other server here with the same 'grpcServer' grpcServer.Serve(lis)
登錄后復(fù)制
這個 stackoverflow 線程可能會幫助您作為您想要實(shí)現(xiàn)的目標(biāo)的示例。該問題提供了一個示例代碼,我認(rèn)為該代碼與您的要求相符。
通過同一連接訪問多個 grpc 服務(wù)






