在 Google Cloud Run 上运行 Python gRPC 服务器

2024-01-15

我有一个基本的概念验证 Python gRPC 服务器。

当我在本地运行 Docker 容器时,我可以向服务器发出请求并在公开的端口上接收响应。

我可以成功地将服务器部署到 Cloud Run,并且我看到该服务在 Cloud Run UI 中运行。

但是,我无法从客户端访问 Cloud Run 版本。

我正在寻找帮助我访问该服务器的建议,无论是对客户端还是服务器的更改。

客户端代码:

with grpc.insecure_channel('...-uc.a.run.app:80') as channel:
  stub = tax_service_pb2_grpc.TaxServiceStub(channel)
  response = stub.GetTaxRate(tax_service_pb2.GetTaxRateRequest(zipcode='12345'))
  print("Tax client received: {}".format(response.tax_rate))

如果我尝试连接到端口 80,我收到以下消息:

    raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
    status = StatusCode.UNAVAILABLE
    details = "Trying to connect an http1.x server"
    debug_error_string = "{"created":"@1575613033.176590200","description":"Error received from peer ipv4:216.239.36.53:80","file":"src/core/lib/surface/call.cc","file_line":1055,"grpc_message":"Trying to connect an http1.x server","grpc_status":14}"

如果我尝试连接到端口 443,我会收到

    raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
    status = StatusCode.UNAVAILABLE
    details = "Trying to connect an http1.x server"
    debug_error_string = "{"created":"@1575613033.176590200","description":"Error received from peer ipv4:216.239.36.53:80","file":"src/core/lib/surface/call.cc","file_line":1055,"grpc_message":"Trying to connect an http1.x server","grpc_status":14}"

服务器代码:

import time
from concurrent import futures

import grpc
from grpc_reflection.v1alpha import reflection

import tax_service_pb2
import tax_service_pb2_grpc


class TaxServicer(tax_service_pb2_grpc.TaxServiceServicer):
  def GetTaxRate(self, request, context):
      return tax_service_pb2.GetTaxRateResponse(tax_rate=1.5)

  def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    tax_service_pb2_grpc.add_TaxServiceServicer_to_server(TaxServicer(), server)
    SERVICE_NAMES = (
        tax_service_pb2.DESCRIPTOR.services_by_name['TaxService'].full_name,
        reflection.SERVICE_NAME,
    )
    reflection.enable_server_reflection(SERVICE_NAMES, server)
    server.add_insecure_port('0.0.0.0:{}'.format(os.environ.get('PORT', 8080)))

    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    logging.basicConfig()
    serve()

服务器端无需进行任何更改。

Cloud Run 使用不安全端口来访问 gRPC 服务,然后在 Google 云边缘和客户端之间添加 SSL。

在我的客户端上,我需要使用系统根证书才能访问服务

with grpc.secure_channel('<app-url>-uc.a.run.app:443', grpc.ssl_channel_credentials()) as channel:
   stub = tax_service_pb2_grpc.TaxServiceStub(channel)
   response = stub.GetTaxRate(tax_service_pb2.GetTaxRateRequest(zipcode='12345'))
   print("Tax client received: {}".format(response.tax_rate))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Google Cloud Run 上运行 Python gRPC 服务器 的相关文章

随机推荐