javaamazon-web-servicesspring-bootredisredis-cache

How to use Redis Cache to store the data in java spring boot application?


I have already a running instance of Redis Cache in AWS Account. How can I use the redis instance using the redis instance Endpoint in my java code to store the data.

I don't have any idea how to start with Redis Cache in java. Please help me out to resolve this.


Solution

  • You can use spring-data-redis by including following dependency.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
        <version>2.2.6.RELEASE</version>    
    </dependency>
    

    Then specify properties as below:

    spring.redis.database=0
    spring.redis.host="Specify URL"
    spring.redis.port=6379
    spring.redis.password=mypass
    spring.redis.timeout=60000
    

    Then using RedisTemplate

    @Autowired
    private RedisTemplate<Long, Book> redisTemplate;
    
    public void save(Book book) {
        redisTemplate.opsForValue().set(book.getId(), book);
    }
    
    public Book findById(Long id) {
        return redisTemplate.opsForValue().get(id);
    }