If you’re here, perhaps, you already know the advantages of Redis, ElastiCache, and Lambda functions; so, I just tell you how to make it work in just a few minutes.

1. Create a simple Redis data structure store

5

I have not used any replicas just for simplicity and my subnet group contains only one subnet. Cluster mode is not enabled as well.

2. Create a role with the required policies for your Lambda using IAM

8

You should, as always, give the minimum privileges required and just to run this sample you should make sure that you provide the policy to grant ​CreateNetworkInterface to your Lambda function, but simply here I have assigned NetworkAdministrator policy to this role!

3. Install AWS SDK

Install AWS SDK for Visual Studio 2017, if you already haven’t (to be on the same page, and perhaps more productive in real life, otherwise it’s optional and you can reinvent the wheel)

4. Create a new Lambda project

1

Note: The unit test that you can add to your project here, won’t appear in your console as the Tests.

5. Select Blueprint (the empty one in this case)

2

Already you have a working Lambda function which is ready to deploy.

6. Add the reference to ServiceStack Radis nuget package

11

Make sure that the package is added to your references. By the way, the reason I have added this version (1.0.3) is that, at the moment, Lambda supports only .netcoreapp1.0 runtime so you should select a compatible library (which is not the case for the latest version), and this package is enough for the sake of this example it works fine.

7. the code to write into and read from Redis

using System;
using Amazon.Lambda.Core;
using ServiceStack.Redis;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace redis_lambda_test
{
    public class Function
    {
        public string FunctionHandler( string input, ILambdaContext context )
        {
            try
            {
                using (var redis = new RedisClient("redis-dss.ia4.0001.use1.cache.amazonaws.com", 6379))
                {
                    var redisUsers = redis.As<Person>();
                    LambdaLogger.Log("redis client created");

                    var user = new Person { Id = redisUsers.GetNextSequence(), Name = input };
                    redisUsers.Store(user);
                    LambdaLogger.Log("user added");

                    var allUsers = redisUsers.GetAll();
                    LambdaLogger.Log("Retrieved users");
                    return allUsers.Count + " " + allUsers[allUsers.Count - 1];
                }
            }
            catch (Exception e)
            {
                LambdaLogger.Log(e.StackTrace);
                return "Oops! something went wrong";
            }
        }
        internal class Person
        {
            public long Id { get; set; }
            public string Name { get; set; }
            public override string ToString()
            {
                return $"{Id} - {Name}";
            }
        }
    }
}

 

Just add a user with the name provided in the input and retrieve it, the return the size of the collection plus your last entry.

Note: as a side note you can see how you enable logging in your lambda; just notice that you can find the logs after each run in CloudWatch in the same region as your Lambda.

8. Publish your function to AWS

910

Notes:

  • The function name that you provide in the first publish will create the Lambda function for you and in the subsequent publishes just use that name again.
  • Assume the role that you created earlier
  • Select a subnet from the VPC you want your Lambda to be there and the Security Group (same VPC and Security Group as your ElastiCache Redis)

9. Test it

1213

Congratulations, It works!