Redis is a fast in-memory data store commonly used for caching and simple data storage. In Spring Boot, Redis is easy to use and perfect for CRUD (Create, Read, Update, Delete) operations. This article explains how to implement basic CRUD operations with Redis in a clear and practical way.
1. Basic Redis Configuration
Spring Boot provides
RedisTemplate to interact with Redis. Once Redis is connected, you can start storing and retrieving data immediately.
Example configuration in
application.properties:
spring.redis.host=localhost
spring.redis.port=6379
Spring Boot will auto-configure Redis for you.
2. Using RedisTemplate
RedisTemplate is the main class used to perform Redis operations.
@Autowired
private RedisTemplate<String, Object> redisTemplate;
This template allows you to work with keys and values easily.
3. Create (Save Data)
To store data in Redis, use
opsForValue() for simple key-value operations.
public void saveUser(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
This saves the value under the given key in Redis.
4. Read (Get Data)
To retrieve data from Redis:
public String getUser(String key) {
return (String) redisTemplate.opsForValue().get(key);
}
Redis returns the value instantly from memory.
5. Update Data
Updating data is the same as saving. Redis will overwrite the existing value.
public void updateUser(String key, String newValue) {
redisTemplate.opsForValue().set(key, newValue);
}
No extra update command is needed.
6. Delete Data
To remove data from Redis:
public void deleteUser(String key) {
redisTemplate.delete(key);
}
This deletes the key and its value permanently.
7. Using Redis with REST API
You can expose Redis CRUD operations via REST endpoints.
@RestController
@RequestMapping("/redis")
public class RedisController {
@Autowired
private RedisService redisService;
@PostMapping("/{key}")
public void save(@PathVariable String key, @RequestBody String value) {
redisService.saveUser(key, value);
}
@GetMapping("/{key}")
public String get(@PathVariable String key) {
return redisService.getUser(key);
}
@DeleteMapping("/{key}")
public void delete(@PathVariable String key) {
redisService.deleteUser(key);
}
}
This makes Redis easy to test using tools like Postman.
image quote pre code