Tim Biegeleisen
Tim Biegeleisen

Reputation: 522264

How to configure Redis cache for session management with UUIDs

I am attempting to configure Redis as cache layer in a Java application. Specifically, the intended use of Redis will be to maintain session state. Each user in the application would be represented by:

I am confused about how to use Redis' hash. The interface for Jedis is:

Jedis#hset(byte[] key, byte[] field, byte[] value)

That is, the Redis hash has a key, which in turn points to another map of fields and values.

What design should I use to:

To the second point above, if I wanted to expire an entry, it would have to be done at the key, and not field, level. But, this would then imply that each UUID would have to be a separate key in the hash, and it is not clear whether that would be good Redis design.

Upvotes: 1

Views: 3258

Answers (1)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 49032

Using Redis hashes for session state is very common. The standard approach is to use the session ID as the key and to use the hash fields for the rest of the session state. This design has the following desirable characteristics:

  • You can fetch the session state in O(1) time.
  • You can set an expiration time for the session.
  • You can store arbitrary amounts of information in the session.

I believe that meets your requirements.

Your use of the phrases "the Redis hash has a key" and "key in the hash" make me think you're misunderstanding how hashes work. The key is the name of the hash, if you will, not a member of it. The HSET signature is specifying which hash you want to modify (the key), and what field and value to set in it.

Here's an example (using Redis commands) of what creating a session might look like:

HMSET session:123 userId 5 last_login 2019-02-13 ...
EXPIRE session:123 2592000

Then you can get session data with:

HGET session:123 last_login

Or set it with:

HSET session:123 last_login 2019-02-18

Upvotes: 6

Related Questions