代码之家  ›  专栏  ›  技术社区  ›  Brian M. Hunt

Python Google Cloud函数连接被peer重置

  •  6
  • Brian M. Hunt  · 技术社区  · 7 年前

    https://issuetracker.google.com/issues/113672049

    此处交叉张贴: https://github.com/GoogleCloudPlatform/google-cloud-python/issues/5879 )

    部署的函数正在调用一个blob get,即。

    from firebase_admin import storage
    
    def fn(request):
      bucket = 'my-firebase-bucket'
      path = '/thing'
      blob = storage.bucket(bucket).get_blob(path)
    

    在函数部署后第一次被调用时,它似乎更容易失败。

    1 回复  |  直到 7 年前
        1
  •  7
  •   timvink    6 年前

    云函数是无状态的,但可以重用以前调用的全局状态。这在中进行了解释 tips these docs .

    使用带有重试的全局状态可以提供更强大的功能:

    from tenacity import retry, stop_after_attempt, wait_random
    from firebase_admin import storage
    
    @retry(stop=stop_after_attempt(3), wait=wait_random(min=1, max=2))
    def get_bucket(storage):
        return storage.bucket('my-firebase-bucket')
    
    @retry(stop=stop_after_attempt(3), wait=wait_random(min=1, max=2))
    def get_blob(bucket, path):
        return bucket.get_blob(path)
    
    bucket = get_bucket(storage)
    
    def fn(request):
      path = '/thing'
      blob = get_blob(bucket, path)
      # etc..
    
        2
  •  0
  •   ProGirlXOXO    6 年前

    您可能需要检查正在创建的客户机数量。

    在优化网络中描述。但是,请注意 未使用2分钟的可能会被系统关闭,并且 进一步尝试使用闭合连接将导致 “连接重置”错误 . 您的代码应该使用 低层次的网络结构。

    https://cloud.google.com/functions/docs/concepts/exec#network

    import os
    from google.cloud import pubsub_v1
    
    # Create a global Pub/Sub client to avoid unneeded network activity
    pubsub = pubsub_v1.PublisherClient()
    
    
    def gcp_api_call(request):
        """
        HTTP Cloud Function that uses a cached client library instance to
        reduce the number of connections required per function invocation.
        Args:
            request (flask.Request): The request object.
        Returns:
            The response text, or any set of values that can be turned into a
            Response object using `make_response`
            <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
        """
    
        project = os.getenv('GCP_PROJECT')
        request_json = request.get_json()
    
        topic_name = request_json['topic']
        topic_path = pubsub.topic_path(project, topic_name)
    
        # Process the request
        data = 'Test message'.encode('utf-8')
        pubsub.publish(topic_path, data=data)
    
        return '1 message published'
    

    https://cloud.google.com/functions/docs/bestpractices/networking#accessing_google_apis