Clojure Redis: Get and Set

For a brief intro to setting up Redis with Clojure using Carmine, see my earlier post on setting up Redis with Clojure.

The most common killer use for Redis is as a key-value store. You simply get and set values in it like in a map. It’s very handy for site wide session storage with web apps, or even in more traditional applications.

Before getting into the first code sample, the naming convention for complex Redis key names is

Breaking that down, use the key names in Redis similar to namespaces in and package names in other languages. Separate groups with colons ( : ). Individual names of groups and actual keys that are multiple words long, separate with dashes ( ).

Here’s a very basic key-value set and get.

Running this function will result in mysecurejwt , Honestly, not that exciting, but often enough for many applications.

Now, let’s look at some of the additions to the simple mapping of keys and values that put Redis on the map. (Little coder joke there.)

First, you can set a timeout on a key-value pair in Redis. This makes the key “volatile”, and after the timeout, it just disappears.

A good use case for a volatile key is storing valid session token for users logged into your app. Often, when a user logs into a web app or other network based app, you want to assign a temporary token that goes away on its own after a certain amount of time (24 hours is common). Using the following code could accomplish that.

The trick here is to use the command, setex. setex takes a key, a second count, and a value as arguments. The above line sets the key my-group:my-key  with value mysecurejwt  to disappear in 24 hours.

If you want to test it in an app, you could use the following code.

Notice that the second time the value is accessed, it has expired because six seconds is up.

Sometimes, you want to invalidate a key. To remove a Redis key, use the del  command.

A common use case of del  would be logging out and expiring the user’s token.

Here’s a larger example in context.

The docs for Carmine are a great place to start if you want to see other ways to use Clojure with Redis.

If you want to see a specific Clojure tutorial, please let me know on Twiter.

Leave a Reply

Your email address will not be published. Required fields are marked *