LoginSignup
9
9

More than 3 years have passed since last update.

AWS Lambda から ElastiCache に接続する

Last updated at Posted at 2018-02-04

やりたいこと

  • AWS Lambda から ElastiCache に接続する
  • boto3 は get/set はできないらしいので他の方法を使う

必要な設定

  • AWS Lambda, ElastiCache を同じVPCにあわせる

redis (クラスターモードが無効) の場合

EC2 にて redis-py をダウンロード

$ pip3 install redis -t ./
  • 生成されるディレクトリを開発環境の index.py と同じディレクトリにコピーする

index.py 作成

index.py
import redis

def handler(event, context):

    r = redis.StrictRedis(host='****.****.0001.apne1.cache.amazonaws.com', port="6379", db=0)

    r.set("key1", "value1")
    print(r.get("key1"))

    return "OK"

または

index.py
import redis

def handler(event, context):

    pool = redis.ConnectionPool(host='****.****.0001.apne1.cache.amazonaws.com', port=6379, db=0)
    r = redis.StrictRedis(connection_pool=pool)

    r.set("key1", "value1")
    print(r.get("key1"))

    return "OK"

以上。

redis (クラスターモードが有効) の場合

EC2 にて redis-py-cluster をダウンロード

$ pip3 install redis-py-cluster -t ./
  • redis-py も依存してるので一緒にダウンロードされる
  • 生成されるディレクトリを開発環境の index.py と同じディレクトリにコピーする

index.py 作成

index.py
from rediscluster import StrictRedisCluster

def handler(event, context):

    startup_nodes = [{"host": "****.****.clustercfg.apne1.cache.amazonaws.com", "port": "6379"}]
    rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True, skip_full_coverage_check=True)

    rc.set("key1", "value")
    print(rc.get("key1"))

    return "OK"

  • クラスターモードが無効の redis には繋がらないのでテスト環境などでは上記実装を切り替える

以上。

9
9
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9