How to Connect AWS Lambda to an Amazon ElastiCache Redis Cluster
Tambe Salome
Posted on September 12, 2023
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.
- 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.
- Select Easy Create for the cluster creation method, and choose Demo for the configuration type.
- Give your cluster a name and a brief description.
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.
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")
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!"
Posted on September 12, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.