Core Data Types in Redis
1. Strings
Strings are the most basic data type — a key maps directly to a value. They can store text, numbers, or serialized objects.
SET key value— Assign a value to a key.GET key— Retrieve the value associated with the key.SETEX key seconds value— Set a key with an expiration time in seconds.SETNX key value— Set the key only if it does not exist (atomic create-if-absent).APPEND key value— Append text to an existing string.MSET key1 val1 key2 val2— Set multiple key-value pairs in one operation.MGET key1 key2— Retrieve multiple values in a single call.
2. Lists
Lists are ordered collections of strings, implemented as doubly linked lists. Ideal for queues and stacks.
LPUSH key element— Add an item to the head of the list.RPOP key— Remove and return the last element.LLEN key— Return the number of elements in the list.LRANGE key start stop— Retrieve elements within a range (0 to -1 returns all).LINSERT key BEFORE/AFTER pivot value— Insert an element before or after a specified value.
3. Sets
Sets are unordered collections of unique strings. Useful for membership testing and grouping.
SADD key member— Add one or more members to the set.SMEMBERS key— Return all members of the set.SISMEMBER key member— Check if a member exists in the set.SINTER key1 key2— Compute the intersection of two sets.SUNION key1 key2— Compute the union of two sets.SDIFF key1 key2— Return elements in key1 but not in key2.SPOP key— Remove and return a random member.
4. Sorted Sets
Sorted sets are like sets but each member has a floating-point score used for ordering.
ZADD key score member— Add a member with a score.ZRANGE key start stop WITHSCORES— Retrieve members in ascending score order.ZREVRANGE key start stop— Retrieve members in descending score order.ZSCORE key member— Get the score of a specific member.ZINCRBY key increment member— Increment a member’s score by a value.ZREM key member— Remove a member from the set.
5. Hashes
Hashes map fields to values, making them ideal for representing objects.
HSET key field value— Set a field in a hash.HGET key field— Retrieve a field’s value.HGETALL key— Return all field-value pairs in the hash.HKEYS key— Return all field names.HVALS key— Return all values.HDEL key field— Delete one or more fields.
Integrating Redis with Spring Boot in IntelliJ IDEA
1. Add Dependencies
Add the Spring Data Redis and caching starter to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2. Configure Redis Connection
In application.yml, specify the Redis server details:
spring:
redis:
host: localhost
port: 6379
database: 0
If no password is set, omit the password field.
3. Configure RedisTemplate Serialization
To avoid encoding issues when storing Java objects, configure the RedisTemplate to use string serialization for keys and values:
package com.sky.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
4. Perform CRUD Operations via Test Class
Create a test class to interact with Redis using the configured template:
package com.sky.test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@SpringBootTest
public class RedisOperationsTest {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
public void testStringOperations() {
ValueOperations<String, Object> ops = redisTemplate.opsForValue();
ops.set("user:name", "Alice");
Object name = ops.get("user:name");
ops.set("session:token", "abc123", 30, TimeUnit.SECONDS);
boolean inserted = ops.setIfAbsent("lock:resource", "locked");
}
@Test
public void testHashOperations() {
HashOperations<String, String, Object> ops = redisTemplate.opsForHash();
ops.put("user:100", "name", "Bob");
ops.put("user:100", "age", "25");
Object userName = ops.get("user:100", "name");
Set<String> fields = ops.keys("user:100");
List<Object> values = ops.values("user:100");
ops.delete("user:100", "age");
}
@Test
public void testListOperations() {
ListOperations<String, Object> ops = redisTemplate.opsForList();
ops.leftPush("task:queue", "send_email");
ops.leftPushAll("task:queue", "log_activity", "update_cache");
List<Object> tasks = ops.range("task:queue", 0, -1);
Object firstTask = ops.leftPop("task:queue");
}
@Test
public void testSetOperations() {
SetOperations<String, Object> ops = redisTemplate.opsForSet();
ops.add("active_users", "user1", "user2", "user3");
Boolean exists = ops.isMember("active_users", "user1");
Set<Object> intersection = ops.intersect("active_users", "premium_users");
}
@Test
public void testSortedSetOperations() {
ZSetOperations<String, Object> ops = redisTemplate.opsForZSet();
ops.add("leaderboard", "player1", 850);
ops.add("leaderboard", "player2", 920);
Set<Object> topPlayers = ops.reverseRange("leaderboard", 0, 2);
ops.incrementScore("leaderboard", "player1", 50);
}
}
Common Use Cases
Redis excels in scenarios requiring speed and concurrency:
- Session caching — Store user sessions to reduce database load.
- Rate limiting — Use
INCRandEXPIREto track request counts per user. - Distributed locks — Leverage
SETNXto coordinate access across microservices. - Real-time leaderboards — Utilize sorted sets to rank users by score.
- Message brokering — Use pub/sub for decoupled event-driven communication between services.
While Redis supports persistence via RDB snapshots and AOF logs, it remains primarily an in-memory system. For large-scale persistent storage, pair it with relational or document databases.