James111
James111

Reputation: 15903

How should I store multiple sessions to a user with Redis?

Assuming a user can have multiple sessions (JWT tokens). Would it be best to store a hashet of tokens where the key is the userId?

E.g key: 1 -> hashet: "token1", "token2", "token3", "token4", "moretokens..."

To then check if a token is valid I'd get the hashset, loop through it and try match a token?

Using a hashet would mean I'd be able to show user there current sessions.

Upvotes: 1

Views: 1639

Answers (2)

Chris Tanner
Chris Tanner

Reputation: 1660

Hashes would be the most efficient way to store the values, as you can store all of a users tokens under the user ID, and check for them directly using HGET, without needing to retrieve them all and loop through them.

Upvotes: 0

for_stack
for_stack

Reputation: 22946

You can use a SET to store the tokens: take user ID as key, and store token list into the SET (as value), which contains unique elements.

// insert single token
sadd userId token1

// insert multiple tokens
sadd userId token2 token3

// insert an existing token will fail
sadd userId token1

// check if a token is valid
sismember userId token1

// get all tokens of a user
smembers userId

Upvotes: 1

Related Questions