If you do not have it already install serverless framework via:
npm install -g serverlessIn any folder run serverless as below:
Copy
Ask AI
>> serverlessServerless: No project detected. Do you want to create a new one? YesServerless: What do you want to make? AWS Node.jsServerless: What do you want to call this project? test-upstashProject successfully created in 'test-upstash' folder.You can monitor, troubleshoot, and test your new service with a free Serverless account.Serverless: Would you like to enable this? NoYou can run the “serverless” command again if you change your mind later.
Inside the project folder create a node project with the command:
Copy
Ask AI
npm init
Then install the redis client with:
Copy
Ask AI
npm install ioredis
Edit handler.js file as below. Replace the Redis URL (copy ioredis url from your
Upstash console).
Copy
Ask AI
var Redis = require("ioredis");if (typeof client === "undefined") { var client = new Redis(REDIS_URL);}module.exports.hello = async (event) => { await client.set("foo", "bar"); let response = await client.get("foo"); return { response: response };};
This example uses ioredis, you can copy the connection string from the
Node tab in the console.
You can also test your function using AWS console. In your AWS Lambda section,
click on your function. Scroll down to the code sections and click on the Test
button on the top right.
Congratulations, now your lambda function inserts entry to your Upstash
database.
Although Redis connections are very lightweight, a new connection inside each
Lambda function can cause a notable latency. On the other hand, reusing Redis
connections inside the AWS Lambda functions has its own drawbacks. When AWS
scales out Lambda functions, the number of open connections can rapidly
increase. Fortunately, Upstash detects and terminates the idle and zombie
connections thanks to its smart connection handling algorithm. Thanks to this
algorithm; we have been recommending caching your Redis connection in serverless
functions.
See the blog post
about the database connections in serverless functions.