DEV Community

Sri
Sri

Posted on

Connecting to Redis cache and working with it

  1. Start Redis Server Make sure Redis is running on the default port 6379. Test it: redis-cli ping Expected: PONG ________________________________________
  2. Add Dependency For Maven: org.springframework.boot spring-boot-starter-data-redis ________________________________________
  3. Configure Redis application.properties spring.data.redis.host=localhost spring.data.redis.port=6379 ________________________________________
  4. 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;
    

    }
    }


  5. 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);
    }


  6. 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";
    }
    }


  7. 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"
}
Enter fullscreen mode Exit fullscreen mode

]
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

  1. Entity class must implements Serializale interface so as to allow @cachale to serialise the response oject.

Top comments (0)