【问题标题】:Not able to subscribe to a topic in dapr using grpc with python无法使用 grpc 和 python 订阅 dapr 中的主题
【发布时间】:2020-04-26 17:25:10
【问题描述】:

我很难找到适用于 python 的 gRPC pub-sub 订阅者模板。

我正在尝试的是这个,但它似乎没有成功。

class DaprClientServicer(daprclient_services.DaprClientServicer):
    def OnTopicEvent(self, request, context):
        if request.topic=="TOPIC_A":
            print("Do something")
            response = "some response"
        return response

server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
daprclient_services.add_DaprClientServicer_to_server(DaprClientServicer(), server)
server.add_insecure_port('[::]:50051')
server.start()

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

我的发布声明如下所示:

client.PublishEvent(dapr_messages.PublishEventEnvelope(topic='TOPIC_A', data=data))

【问题讨论】:

    标签: python grpc publish-subscribe


    【解决方案1】:

    旧答案(Dapr 的 Python-SDK API 在此之后发生了显着变化)

    在做了一些研究后,我发现我跳过了这一步。 那么订阅者的工作方式是这样的:

    1. 订阅一个主题。 (缺少步骤)

    2. 处理发布到订阅主题的消息。

    这样做对我有用:

    # Our server methods
    class DaprClientServicer(daprclient_services.DaprClientServicer):
        def GetTopicSubscriptions(self, request, context):
            # Dapr will call this method to get the list of topics the app
            # wants to subscribe to. In this example, we are telling Dapr
            # To subscribe to a topic named TOPIC_A
            return daprclient_messages.GetTopicSubscriptionsEnvelope(topics=['TOPIC_A'])
    
        def OnTopicEvent(self, request, context):
            logging.info("Event received!!")
            return empty_pb2.Empty()
    
    
    # Create a gRPC server
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    daprclient_services.add_DaprClientServicer_to_server(
        DaprClientServicer(), server)
    
    # Start the gRPC server
    print('Starting server. Listening on port 50051.')
    server.add_insecure_port('[::]:50051')
    server.start()
    
    # Since server.start() doesn't block, we need to do a sleep loop
    try:
        while True:
            time.sleep(86400)
    except KeyboardInterrupt:
        server.stop(0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-18
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多