DEV Community

Tambe Salome
Tambe Salome

Posted on

How to Connect AWS Lambda to an Amazon ElastiCache Redis Cluster

Introduction

Amazon's ElastiCache is a service that enables you to launch, manage, and scale a distributed in-memory cache. It has multiple use cases caching, real-time analysis, machine learning, and session storage.

The focus of this tutorial would be on the caching use case with Redis. Applications that already use Redis can use ElastiCache with very little modifications.


Note: Make sure to delete your cluster when you are done using it in order not to incur additional cost. Visit this site to see more about ElastiCache pricing


Creating an ElastiCache Redis Cluster

  • From your AWS Management Console, click on Services and navigate to Database where you would find ElastiCache. Click on it to open your ElastiCache console.

Locate ElastiCache

  • In the side bar, under Resources, click on Redis Cluster. The window show you all Redis clusters you have. To create a new cluster, click the Create Redis Cluster at the top.

Redis Cluster

  • Select Easy Create for the cluster creation method, and choose Demo for the configuration type.

creation method

  • Give your cluster a name and a brief description.

cluster info

  • Under Connectivity, set the network type to IPv4, select Choose an existing subnet group and select the subnet group we used for the Lambda function.

  • Click on Create to create your resource.

Connecting the Redis Cluster to a Lambda Function.

Learn how to setup an AWS Lambda function from from this article

In the Lambda function, navigate to the Configuration tab and on the side panel select VPC.

update sg

In order to connect the Redis instance to the Lambda function, add the security group that the Redis instance belongs to the Lambda function.

Click on Edit and under Security groups, select the Redis instance's security group and then save to update your configuration.

Import Redis in your function and include the redis connection string in your code. For python:

from redis.cluster import RedisCluster

cache = RedisCluster(host="mycache.xxxx.xxx.xxx.cache.amazonaws.com", port="6379")

Enter fullscreen mode Exit fullscreen mode

The host can be the the Configuration endpoint if you have only one node, or the Primary endpoint or the endpoint of the node you need to assess. In this tutorial, the configuration endpoint is used which can be found under Cluster details in your redis cluster's dashboard.

You can test your configuration with this piece of code:

if (cache.exists('names')) :
        return {
            'statusCode': 200,
            'body': cache.get('names')
       }
else :
        cache.set('names', "hello world")
        return "Done!"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)