So far I was using Redis as distributed session storage (it’s quite fine when integrating different systems), or fast application cache. The Spring Session project uses, among others, Redis and it solves in an easy way some problems I met in past like parallel sessions management, integration with Spring Security. Because of that, it’s worth to mention a few useful commands to work with Redis. These are basics but gathered in one place.
# simple crud
redis-cli set key value
redis-cli get key
redis-cli mget key1 key2
# working with hashes
redis-cli HMSET parent:key key1 value1 key2 value2
# to red data from hash we can use hgetall, hvals, hkeys parent:key or hget parent:key key1
# all keys
redis-cli --scan --pattern '*'
redis-cli keys '*'
# get a type of unknown key
redis-cli type spring:session:sessions:6adb75ed-9278-4c83-ae78-5bf139aec14d
# when we have a type of key, we can fetch data
# when data is hash
redis-cli hgetall spring:session:sessions:6adb75ed-9278-4c83-ae78-5bf139aec14d
redis-cli hget spring:session:sessions:6adb75ed-9278-4c83-ae78-5bf139aec14d sessionAttr:SPRING_SECURITY_CONTEXT
# when data is string
redis-cli get spring:session:sessions:expires:6adb75ed-9278-4c83-ae78-5bf139aec14d
# when data is set
redis-cli smembers spring:session:index:org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME:user@example.com
# delete all
redis-cli FLUSHALL
What else Redis can do for us? We can:
– increment values for key – INCR key
– use transactions for our queries – MULTI, SET, INCR, EXEC
– lists with possibility of adding and removing elements, but also using them as queues – RPUSH/LPUSH, LRANGE, LLEN, LREM, LPOP/RPOP, RPOPLPUSH
– sets with operations on them – SADD key value, SMEMBERS, SINTER, SDIFF, SUNION, SUNIONSTORE. Sorted sets with scores and range operations, unions of sets, and aggregations.
– expire data with time to live – EXPIRE key ttlInSeconds
– pub-sub mechanisms – SUBSCRIBE key, BRPOP, etc.
– quite advanced durability, clustering, data dumping with snapshots