Redis can be used as a cache as well as a session store for a Spring Boot applications. As a cache, Redis is used to store the results of queries to the database. This reduces the number of queries to the database and improves performance. As a session store, Redis is used to store the session information for a web application.
Add the following dependencies to the pom.xml
file to configure Redis for the Contoso Fiber application.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis<artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
To enable caching, we need to
- Enable caching in the application with the
@EnableCaching
annotation - Configure the Redis cache manager
- Configure the connection to Redis from the application
- Use the @Cacheable annotation on the methods that we want to cache
In the main application src/contoso-fiber/src/main/java/com/contoso/cams/CamsApplication.java
, add the @EnableCaching
annotation to the CamsApplication
class.
@SpringBootApplication
@EnableCaching
public class ContosoFiberApplication {
public static void main(String[] args) {
SpringApplication.run(ContosoFiberApplication.class, args);
}
}
We will configure the Cache Manager with a bean in the src/contoso-fiber/src/main/java/com/contoso/cams/config/RedisCacheConfig.java
file.
@Configuration
public class RedisCacheConfig {
@Bean
public RedisCacheConfiguration cacheConfiguration() {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.prefixCacheNameWith("com.contoso.cams.")
.entryTtl(Duration.ofMinutes(60))
.disableCachingNullValues()
.serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return config;
}
@Bean
public RedisCacheManager cacheManager(RedisCacheConfiguration config, RedisConnectionFactory connectionFactory) {
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.build();
}
}
Spring Data Redis properties come from the application.properties
file. The following properties are used to configure the connection to Redis.
spring.data.redis.host=localhost
spring.data.redis.port=6379
The @Cacheable
annotation is used to cache the results of a method. The @Cacheable
annotation will be used on the getAccount
method in the AccountService
class. The @CachePut
annotation will be used on the updateAccount
method in the AccountService
class. You can use the @CacheEvict
annotation to remove an item from the cache.
package com.contoso.cams.account;
@Service
@CacheConfig(cacheNames={"accounts"})
public class AccountService {
@CachePut(value="account-details", key="#accountDetail.accountId")
public AccountDetail updateAccount(AccountDetail accountDetail) {
}
@CachePut(value="account-details", key="#id")
public AccountDetail setActive(Long id, boolean isActive) {
}
@Cacheable(value="account-details", key="#id")
public AccountDetail getAccountDetail(Long id) {
}
}
In Contoso Fiber CAMS, Redis is used to store Spring Session that is used to manage the session information for a web application. In a Spring Boot application, Spring Session is configured with the spring-session-data-redis
dependency in the pom.xml
file.
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
To enable Spring Session, add the following properties to the application.properties
file.
# Spring Session to leverage Redis to back a web application’s HttpSession
spring.session.redis.flush-mode=on-save
spring.session.redis.namespace=spring:session
Now that we have configured the application to use Redis, we can run the application and see the results in Redis. Click on an account and then go to the Redis CLI to see the results. Our keys have the prefix com.contoso.cams
.
docker exec -it contoso_fiber_redis bash
root@redis:/data# redis-cli
127.0.0.1:6379> keys *
1) "com.contoso.cams.account-details::1"
2) "spring:session:sessions:05625b53-9a7e-4a01-bd97-8995fc902060"
Get the account details from Redis.
127.0.0.1:6379> get com.contoso.cams.account-details::1
"{\"@class\":\"com.contoso.cams.account.AccountDetail\",\"accountId\":1,\"customerId\":1,\"address\":\"123 Main St.\",\"city\":\"Burlington\",\"customerFirstName\":\"Nick\",\"customerLastName\":\"Dalalelis\",\"customerEmail\":\"[email protected]\",\"customerPhoneNumber\":\"617-528-5544\",\"selectedServicePlanId\":1,\"active\":false,\"supportCases\":[\"java.util.ArrayList\",[]]}"