- Start Redis Server Make sure Redis is running on the default port 6379. Test it: redis-cli ping Expected: PONG ________________________________________
- Add Dependency For Maven: org.springframework.boot spring-boot-starter-data-redis ________________________________________
- Configure Redis application.properties spring.data.redis.host=localhost spring.data.redis.port=6379 ________________________________________
-
Define a RedisTemplate Bean (Optional)
@Configuration
public class RedisConfig {@bean
public RedisTemplate redisTemplate(
RedisConnectionFactory connectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); return template;}
}
-
Use RedisTemplate
Store Data
@Service
public class RedisService {@Autowired
private RedisTemplate redisTemplate;public void save(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
}
Read Data
public String get(String key) {
return (String) redisTemplate.opsForValue().get(key);
}
Delete Data
public void delete(String key) {
redisTemplate.delete(key);
}
-
Controller Example
@RestController
@RequestMapping("/redis")
public class RedisController {@Autowired
private RedisService redisService;@PostMapping("/{key}/{value}")
public String save(
@PathVariable String key,
@PathVariable String value) {redisService.save(key, value); return "Saved";}
@GetMapping("/{key}")
public String get(@PathVariable String key) {
return redisService.get(key);
}@DeleteMapping("/{key}")
public String delete(@PathVariable String key) {
redisService.delete(key);
return "Deleted";
}
}
Caching with Redis
Enable caching:
@SpringBootApplication
@EnableCaching
public class Application {
}
Use cache annotations:
@Cacheable("users")
public User getUser(Long id) {
return userRepository.findById(id).orElse(null);
}
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
execute Get URL in postman:
http://localhost:8080/book/getAllBookDetails
output:
{
"id1": 6,
"author": {
"authorId": 1,
"authorName": null,
"contactNumber": null,
"state": null
},
"name": "PHYTHON"
}
]
REDIS in command prompt:
127.0.0.1:6379> keys *
1) "Books::6"
127.0.0.1:6379>
Step 2:
initialising delete method with
@CacheEvict(value = "Books", key = "#bookIDFromRequest")
@DeleteMapping("/DeleteBookDetails/{bookIDFromRequest}")
public ResponseEntity DeleteBookDetails(@PathVariable int bookIDFromRequest) {
log.info("entering DeleteBookDetails");
String upDateBookStatus= bookService.DeleteBookDetailsService(bookIDFromRequest);
log.info("upDateBookStatus "+upDateBookStatus);
ErrorTemplate error = new ErrorTemplate();
if(upDateBookStatus.equalsIgnoreCase("DeleteBook Failed")){
error.setStatusCode(200);
error.setMessage("book id not found");
return ResponseEntity.status(400).body("Book id not found");
}
Common Startup Error
If you see:
Unable to connect to Redis
Connection refused: localhost:
Points to remember
- Entity class must implements Serializale interface so as to allow @cachale to serialise the response oject.
Top comments (0)