Getting started with Redis on Lumen
You developing a RESTful API on Lumen or simply require a in-memory data storage/database for quick caching purposes. Let's talk about Redis.
As per the website;
“Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries.”
As per me; I’ve been using it for my own RESTful service and all I can tell you is that it’s fast and very simple to use – saving me lots of time in development. Furthermore, it’s easy on the resources.
Let us jump right into it.
Note: If you haven’t started working with Composer yet – this requires that. So go ahead Get Started with Composer first.
First off, Redis is a service that needs to be running to power your application. Head over to https://redis.io/ download and install it.
If you’re on Windows 10, I’d suggest using the Ubuntu Bash terminal that now comes along with it.
Once Redis is up and running, head over to your Lumen project and require Redis. Lumen supports Redis so that makes it much easier for us.
Make sure you’ve uncommented
composer require predis/predis (~1.0)
composer require illuminate/redis (5.2.*)
- Register it in
$app->register(Illuminate\Redis\RedisServiceProvider::class);in the file, under Register Service Providers.
- As per the Lumen docs; If you have not called
bootstrap/app.phpfile, then you should call
bootstrap/app.phpfile to ensure the Redis database configuration is properly loaded.
- Make sure your
.envLumen config file has this set
CACHE_DRIVER=redis. (If you have
.env.exampleinstead; rename it to .
And that’s it! Hit the RedisPHP docs for all the commands.
To use it in Lumen, you can call it these ways
The reason I recommend
app('redis') is because it can be called anywhere, including closures and so on.
Checking if a Key exists:
Setting a key/value:
Getting a value by key:
Setting an expiry for the key:
And you’re good to go!
If you’re wondering what REST API I was talking about, It’s Jikan; an unofficial API platform that handles over 5,000 requests daily!