登录
首页 >  Golang >  Go问答

实现grpc的api方法是什么?

来源:stackoverflow

时间:2024-02-21 22:51:25 279浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《实现grpc的api方法是什么?》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我使用了官方文档https://grpc.io/docs/languages/go/basics/,但是实现后,出现了问题。 当我创建 tcp 服务器时,我必须指定主机和端口(在我的例子中为 mcrsrv-book:7561)。 但是如果我想为 grpc 实现另一个 api 该怎么办?我是否需要在新端口上启动另一台服务器(例如 mcrsrv-book:7562)? grpc中的路由和api是如何实现的?

我的服务器代码是:

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)
}

我认为除了为每个 grpc 服务打开单独的端口之外,还应该有其他选择。

grpc中的api是如何实现的?


正确答案


如果您想将同一地址用于不同的服务,只需在启动 grpc 服务器之前重新注册其他服务即可。

grpcServer := grpc.NewServer(opts...)
pb.RegisterRouteGuideServer(grpcServer, newServer())

#register other server here with the same 'grpcServer'

grpcServer.Serve(lis)

这个 stackoverflow 线程可能会帮助您作为您想要实现的目标的示例。该问题提供了一个示例代码,我认为该代码与您的要求相符。

通过同一连接访问多个 grpc 服务

本篇关于《实现grpc的api方法是什么?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>