Home > Enterprise >  How to access Memcache from AWS Lambda?
How to access Memcache from AWS Lambda?

Time:10-05

I have difficulty in connecting my Lambda with AWS Memcache. I'm using the below code snippet, I don't see any error logs and the function is getting timed out. Can you suggest me what went wrong ?

const MemcachePlus = require("memcache-plus");

const client = new MemcachePlus("test_memcached.cfg.use1.cache.amazonaws.com:11211");
exports.index = async (event) => {
    try {
      await client.set("firstName", "Victor", 10000);
      console.log("Successfully set the key firstName");

      const firstName = await client.get("firstName");
      console.log(`Successfully got the key firstName: ${firstName}`);
    } catch (e) {
      console.log("error", e);
    }
}

CodePudding user response:

  1. Make sure you turn on the DNS hostname for your VPC by looking at this documentation to guide you https://docs.aws.amazon.com/vpc/latest/userguide/vpc-dns.html and the Memcached URL in CloudFormation stack as an output so you're able to add it as an environment variable to your lambda
  2. 'Connect' your lambda to your VPCs subnets & security group. This is how I do it using serverless framework, should look pretty similar when using CloudFormation (https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html)
myLambdaFunc:
  handler: src/myLambdaFunc.handler
  vpc:
    securityGroupIds:
      - Fn::ImportValue: myapp-${{self:provider.stage}}-PrivateVPCLambdaSGID
    subnetIds:
      - Fn::ImportValue: myapp-${{self:provider.stage}}-PrivateVPCSubnet1Ref
      - Fn::ImportValue: myapp-${{self:provider.stage}}-PrivateVPCSubnet2Ref
  environment:
    ELASTIC_CACHE_CONNECTION_URL:
      Fn::ImportValue: myapp-${{self:provider.stage}}-ECURL
  1. Install Memached library for the language/framework you're using and connect using the env variable that has been passed
  • Related