如何在Golang的GRPC中限制客户端的并发连接数

huangapple go评论107阅读模式
英文:

How to limit concurrent connections from client in Golang GRPC

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是GRPC的新手。

我有一个任务:
我需要在Golang的GRPC中实现一个服务。

服务包含以下功能:

1)接收来自客户端的图像并保存它们。
2)显示已保存图像的列表。

问题是如何限制来自客户端的并发连接:

下载/保存文件(图像)- 10个并发请求。

获取已保存消息列表- 100个并发请求。

英文:

I'm a newbie in GRPC.

I have a task:
I have to implement a service in Golang GRPC.

Service with functions:

  1. Accepts image from client and saves them.
  2. Shows a list of saved images.

Question is how to limit conccurent connections from client:

to download/save files(images) - 10 conccurent requests.

to get list of saved messages - 100 conccurent requests.

答案1

得分: 0

根据您的评论,看起来您只想检查特定RPC函数的进行中调用数量。您可以使用标准的Go功能来实现这一点(相同的方法也适用于任何函数)。例如,将计数器添加到您的服务结构体中:

type Server struct {
  // ...
  downloadCount atomic.Int32
  // ...
}

然后在处理调用时使用该计数器:

func (s *Server) Download(context context.Context, req *pbpkg.DownloadRequest) (*pbpkg.DownloadRequest, error) {
  inProgressCount := downloadCount.Add(1)
  defer downloadCount.Add(-1) // 完成后减少计数器

  if inProgressCount > 10 {
    return nil, status.Errorf(codes.ResourceExhausted, "Download limit hit")
  }
  // 在这里执行操作
}

请注意,我使用了atomic.Int32;还有其他方法(如sync.Mutexchan等),但重要的是要考虑竞态条件。

我相信还有其他方法(例如:go-concurrency-limits),但通常简单的方法是最好的!

英文:

Base on your comments it looks like you just want to check how many in-progress calls there are to a specific RPC function. You can do this with standard Go functionality (the same approach can be used for any function). For example; as a counter to your service struct:

type Server struct { ...
 ...
  downloadCount atomic.Int32
 ...
}

Then use that when processing the call:

func (s *Server) Download(context context.Context, *pbpkg.DownloadRequest) (*pbpkg.DownloadRequest, error){
   inProgressCount := downloadCount.Add(1)
   defer downloadCount.Add(-1) // decrease counter when done

   if inProgressCount  > 10 {
      return nil, status.Errorf(codes.ResourceExhausted, "Download limit hit")
   }
   // Do stuff here
}

Note that I've used atomic.Int32; there are other approaches (sync.Mutex, chan etc) but it is important that you consider race conditions.

I'm sure there are other approaches (e.g.) but often the simple approach is best!

huangapple
  • 本文由 发表于 2023年6月11日 22:30:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450961.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定