Note: the instructions below assume you are using MacOS, Ubuntu or Debian.
Serverless functions and state
One of the core values of Serverless functions is the fact that they are stateless. This means that a function invocation can’t depend on pieces of data collected or computed by other functions. To enable state, it is common to use reliable repositories such as Redis. In this tutorial you will walk through building a simple function that inserts and retrieves values from a Redis instance.
Note: this tutorial is not intended to teach you how to setup Redis. You can use cloud hosted Redis services or set it up yourself on a container or VM. You will need the Redis port, host URI and password to complete the tutorial.
1. Connect to Redis
You will use the ioredis package to interface with Redis. You will also need to collect a few configuration settings for your Redis instance.
Create the function
Install the ioredis npm package
Configure your Redis connection parameters
Declare the environment variables needed for Redis by editing the binaris.yml file as below:
Set the values to the environment variables:
Add the Redis connection code
At the top of the function.js file, paste the code below:
2. Insert and fetch data
In this section you will reconstruct your function code to read and write to Redis.
Read processing instructions
This section reads the Redis key, data and method (select or insert) from the function body.
Insert to Redis
This section inserts the value field in the request body into key in the Redis database.
Read from Redis
This section reads the data stored in key.
Your function should now look like:
3. Deploy and Invoke the function
Insert data into Redis
Read data from Redis
You now have a function deployed that uses Redis to store and read data!
To learn more about Binaris functions, review the below documents: