Redis Caching example with Ballerina !

Manuri Amaya Perera
Ballerina Swan Lake Tech Blog
2 min readJul 21, 2018

--

Let’s quickly introduce the key words.

Ballerina is a programming language for integration. To be more accurate, Ballerina is designed to fill the gap between integration focused products and general purpose programming languages!

Redis is an open source, in-memory data structure store, used as a database, cache and message broker.

WSO2 provides a Ballerina package which includes a client to perform operations with a Redis database. Today we are going write a simple Ballerina program for a Redis use case!

Enough talking. Most of you like to run some code first and see it working first. Let’s do it.

Follow these steps to get the environment ready.

  1. Install Ballerina 0.980.1. You can download the Linux/MacOS/Windows installed from here.
  2. Install Ballerina Redis package. You can download the package from GitHub releases of the package. Inside the package zip archive you can find a installer script. It will install the package in seconds.
  3. Install Redis database in your machine/any remote server. Redis website has simple instructions for installation. They provide a Redis docker image too!

Following is the high level picture of what we are going to do.

We have a service which calls a backend and passes the response to the client. Now a Redis database used as an LRU cache comes into the picture. Now instead of calling the backend each time, we check whether the response is cached and return the cached response to the client.

Here is our backend service. This runs on port 9000. Has one resource which simply creates a JSON payload and sends to the client. Please note that a real world back-end could be more complex and a back-end call may be more expensive.

Here is the service. This runs on port 9000. This calls the backend above and passes the response to the client. Before calling the backend it checks the cache. Backend will be called only the response is not in the cache. In that case the response will be added to the cache with an expiry time.

You can run the two services as follows.

ballerina run <path>/dummy-backend.bal

ballerina run <path>/dummy-api.bal

Now send a request.

curl -v http://localhost:9090/dummyService/getData

You should get a response as follows.

{ “Score” : 1 }

--

--

Manuri Amaya Perera
Ballerina Swan Lake Tech Blog

I am an Engineer at WSO2. Currently working in the Ballerina team. Mainly contributing to Ballerina data client area. My GitHub URL: https://github.com/manuri