I want to use caching between c# Lambda calls, I understand if the Lambda starts from cold this wouldn't be possible, but if it is called many times within a short period can we use a cache.
I have tried by creating a static variable, but this seems to be reinitialised after each call?
Anyone have any ideas? Here is an example where I want to increase the TestCache variable by 1 each time, however this always returns 1.
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using System.Collections.Generic;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace MyTestLambda
{
public class Global
{
private readonly Dictionary<string, string> allOriginHeaders = new Dictionary<string, string>
{
{ "Access-Control-Allow-Origin", "*" }
};
public static int TestCache = 0;
public APIGatewayProxyResponse Handler(APIGatewayProxyRequest apigProxyEvent)
{
TestCache += 1;
return new APIGatewayProxyResponse
{
Body = TestCache.ToString(),
StatusCode = 200,
Headers = allOriginHeaders
};
}
}
}
- UPDATED *
I have realised that actually my code does cache, but there must be multiple instances created. In my case I was load testing throwing 500 requests at once, which all came back the same, however when I tested one by one doing it manually, then the numbers did increase. I am going to look at elastic caching as a better approach going forward as per the answer below.