#1
Redis is not only about simple key-value pairs. It also supports powerful data structures like Hashes and Lists, which are very useful in real applications. This article explains how to use Redis Hashes and Lists in Spring Boot in a simple and practical way.

1. Why Use Hashes and Lists

  • Hashes are perfect for storing structured objects (like user profiles).
  • Lists are useful for ordered data (queues, logs, recent activities).
They help reduce complexity and improve performance compared to storing everything as plain strings.

2. RedisTemplate Setup

You can reuse the same RedisTemplate configuration from basic Redis usage.
@Autowired
private RedisTemplate<String, Object> redisTemplate;
Spring Boot automatically handles the connection.

3. Using Redis Hash (Create & Update)

Redis Hash stores multiple fields under one key.
public void saveUserHash(String key, String field, String value) {
    redisTemplate.opsForHash().put(key, field, value);
}
example usage:
  • Key: user:1
  • Field: name
  • Value: John

4. Read Data from Redis Hash

To get a single field value:
public Object getUserField(String key, String field) {
    return redisTemplate.opsForHash().get(key, field);
}
To get all fields:
public Map<Object, Object> getAllUserData(String key) {
    return redisTemplate.opsForHash().entries(key);
}

5. Delete Hash Data

Remove a specific field from a hash:
public void deleteUserField(String key, String field) {
    redisTemplate.opsForHash().delete(key, field);
}
Or delete the whole hash:
redisTemplate.delete(key);

6. Using Redis List (Create Data)

Redis List keeps values in order.
public void addToList(String key,String value) {
    redisTemplate.opsForList().rightPush(key, value);
}

This is useful for logs, messages, or queues.

7. Read Data from Redis List

Get all values from a list:

public List<Object> getList(String key) {
    return redisTemplate.opsForList().range(key,0,-1);
}
Get and remove the first item (queue behavior):
public Object popFromList(String key) {
    return redisTemplate.opsForList().leftPop(key);
}

8. Using Hashes and Lists with REST API

Example REST controller:
@RestController
@RequestMapping("/redis")
public class RedisDataController {
    @Autowired
    private RedisService redisService;
    
    @PostMapping("/hash/{key}/{field}")
    public void saveHash(@PathVariable String key
                         @PathVariable String field,
                         @RequestBody String value) {
        redisService.saveUserHash(key, field, value);
    }
    
    @PostMapping("/list/{key}")
    public void pushList(@PathVariable String key,
                         @RequestBody String value) {
        redisService.addToList(key,value);
    }
}
This makes testing easy with Postman or curl.
#ads

image quote pre code