Thursday, 19 March 2015

Redis Cache in Java (with Spring Boot)

Redis is a high-performance, in-memory key-value store often used for caching in Java applications. When integrated with Spring Boot, it becomes very easy to use with annotations like @Cacheable, @CachePut, and @CacheEvict.

🔧 Step-by-Step: Using Redis Cache in Java (Spring Boot)


✅ 1. Add Maven Dependency (spring-boot-starter-data-redis)

xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>

You may also need:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>

And for embedded Redis during testing (optional):

xml
<dependency> <groupId>it.ozimov</groupId> <artifactId>embedded-redis</artifactId> <version>0.7.2</version> </dependency>

✅ 2. Enable Caching in Main Class

@SpringBootApplication @EnableCaching public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }

✅ 3. Configure Redis in application.properties

properties

spring.cache.type=redis spring.redis.host=localhost spring.redis.port=6379

✅ 4. Example Entity and Repository

Entity (e.g., Department.java):


@Data @AllArgsConstructor @NoArgsConstructor public class Department implements Serializable { private Long id; private String name; private String code; }

Repository:


@Repository public class DepartmentRepository { private Map<Long, Department> departmentMap = new HashMap<>(); public Department findById(Long id) { simulateSlowService(); return departmentMap.get(id); } private void simulateSlowService() { try { Thread.sleep(3000); // simulate DB call } catch (InterruptedException e) { e.printStackTrace(); } } }

✅ 5. Cache Logic with @Cacheable


@Service public class DepartmentService { @Autowired private DepartmentRepository repository; @Cacheable(value = "departments", key = "#id") public Department getDepartmentById(Long id) { return repository.findById(id); } @CacheEvict(value = "departments", key = "#id") public void deleteDepartment(Long id) { // deletion logic here } @CachePut(value = "departments", key = "#department.id") public Department updateDepartment(Department department) { // update logic here return department; } }

✅ 6. Redis Console

Make sure Redis is running:

bash

redis-server

You can view keys via:

bash

redis-cli 127.0.0.1:6379> KEYS *

✅ Sample Behavior

  1. First call to getDepartmentById(1) → takes 3 seconds (simulated)

  2. Next call → instant (from Redis cache)


✅ Summary

AnnotationPurpose
@CacheableCaches the result of a method call
@CachePutUpdates the cache after method call
@CacheEvictRemoves entry from cache
@EnableCachingEnables Spring’s cache abstraction

1 comment: