Python - 与AWS Redis超时的连接

时间:2018-03-26 09:46:42

标签: python redis

目前我有这个python代码来测试AWS redis连接,它失败了连接超时。你能帮我解决一下吗?

import redis, time, datetime, sys

endpoint='myred-0041.dpchko.0001.amazonaws.com'

def prepareConn(endpoint):
    r = redis.StrictRedis(host=endpoint, port=6379, db=0, socket_timeout=1)
    return r

r = prepareConn(endpoint)

while True:
    print(datetime.datetime.now())
    try:
        print(r.set('foo','bar'))
    except:
        print "Unexpected error:", sys.exc_info()[0]
    time.sleep(1)

2 个答案:

答案 0 :(得分:0)

我找到了解决方案,AWS有一些限制,使我的本地PC无法连接到AWS Redis,然后我在本地https://redis.io/上安装了Redis,并将端点替换为endpoint ='http://localhost'

但是在生产deploymet上,我使用AWS Redis,并且工作正常

答案 1 :(得分:0)

该技术是尝试将状态保持在环境变量中

def session():
    if "REGION_NAME" in os.environ.keys():
        pass
    else:
        fname = "/tmp/aws-secrets.json"
        if not os.path.exists(fname):
            fname = os.path.join(os.path.dirname(os.path.realpath(__file__)), "aws-secrets.json")
        with open(fname, "r") as f:
            envjson = json.load(f)
        for k, v in envjson.items():
            os.environ[k] = v
    sess = boto3.session.Session(region_name=os.environ["REGION_NAME"],
                                 aws_access_key_id=os.environ["ACCESS_ID"],
                                 aws_secret_access_key=os.environ["ACCESS_KEY"])
    return sess

def get_redis_endpoint(cluster_id="redis-sensorvenv"):
    ec = session().client("elasticache")

    resp = ec.describe_cache_clusters(CacheClusterId = cluster_id, ShowCacheNodeInfo=True)
    return resp["CacheClusters"][0]["CacheNodes"][0]["Endpoint"]["Address"]

仅供参考,我使用boto3获得了终点

{
  "_index": "bpm-aggregate-19.07",
  "_type": "_doc",
  "_id": "b80b708c-d617-4dd4-89cd-6f1efeef927a.ebab442f-d9ad-423f-862c-d803eae3c99a.7330.28",
  "_version": 33,
  "_score": null,
  "_source": {
    "bpm": {
      "sequenceId": 33
    },
    "source": {
      "bpm": {
        "version": "2064.117680c1-e266-4dac-ae23-fb8bf948003a",
        "name": "Check Request"
      },
      "parent": {
        "parent": {
          "bpm": {
            "version": "2064.117680c1-e266-4dac-ae23-fb8bf948003a",
            "name": "Payment Order",
            "documentation": ""
          },
          "id": "c1c49bbe-b5f2-4c49-9dd6-7812a94d8ba3",
          "type": "wle:processApplication"
        },
        "id": "b80b708c-d617-4dd4-89cd-6f1efeef927a",
        "instance": {
          "bpm": {
            "state": "Active"
          },
          "id": "7330"
        },
        "type": "bpmn:process"
      },
      "id": "99bc462b-312d-43d0-8548-715b19f6ee5b",
      "type": "bpmn:userTask"
    },
    "context": {
      "bpm": {
        "starting-process-instance": "b80b708c-d617-4dd4-89cd-6f1efeef927a.ebab442f-d9ad-423f-862c-d803eae3c99a.7330"
      },
      "trace-id": "3f605c67-1e21-47bb-91b3-b87cd24d26da",
      "span-id": "8d07ccec45054267"
    },
    "@taskCompletedOverdue": 1,
    "task": {
      "user": {
        "bpm": {
          "name": "John Doe"
        },
        "id": "jdoe3"
      },
      "time": {
        "complete": "2019-07-29T10:17:39.823Z",
        "start": "2019-07-29T05:08:02.180Z",
        "open": "2019-07-29T10:17:23.930Z",
        "assign": "2019-07-29T05:08:02.340Z"
      },
      "kpi": {
        "timeToCompleteFromOpen": 0.26488333333333336,
        "timeToComplete": 309.62738333333334,
        "timeToFirstOpen": 309.3598333333333
      },
      "name": "Check Request",
      "state": "Completed",
      "team": {
        "bpm": {
          "name": "All Users"
        },
        "id": "All Users_T_da7e4d23-78cb-4483-98ed-b9c238308a03.d158d9ca-4d62-4c73-9ddd-dfa70b37f398"
      }
    },
    "@lastUpdateEventType": "bpmnx:ACTIVITY_COMPLETED",
    "@timestamp": "2019-07-29T10:17:40.293Z",
    "system": {
      "bpm": {
        "bpmCellName": "bpmWorfklowCenterCell01"
      },
      "id": "ebab442f-d9ad-423f-862c-d803eae3c99a"
    },
    "@version": "1",
    "category": "bpmnx:BPD",
    "business-events-extension-version": "bpmn/1.0.0",
    "business-events-envelope-version": "1.0.0",
    "@lastUpdateEventSequenceId": 33,
    "@lastUpdateTime": "2019-07-29T12:17:39.823+02:00"
  }
}