使用Spring Boot集成Redis缓存
在本文中,我们将了解如何将Redis缓存与Spring Boot集成。我们将学习如何在Spring Boot缓存中配置Redis数据。
让我们首先看看将Redis导入Spring Boot应用程序所需的依赖项。
依赖项
// Adding spring-boot cache & redis dependencies <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> <version>2.4.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.4.3</version> </dependency>
配置
添加Redis依赖项后,您现在需要执行一些配置才能在您的项目中使用它。Spring Boot将自动配置一个Redis缓存管理器,但使用默认属性。我们可以修改此配置并根据我们的需求更改它。
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(60)) // Changing the cache TTL
.disableCachingNullValues()
.serializeValuesWith(SerializationPair.fromSerializer(newGenericJackson2JsonRedisSerializer()));
//Defining serialization to retrieve data
}修改配置使我们可以更好地控制基本的缓存配置。例如,我们可以更改默认的生存时间值,并自定义默认的序列化策略以进行动态缓存创建,如上所示。
示例
让我们以一个示例为例,我们有一个**EmployeeService**组件,它从数据库检索员工信息。由于我们需要获取员工详细信息用于多种用途,我们需要此数据快速响应,这就是我们使用Redis缓存的原因。让我们为此创建一个集成测试。
@Import({ CacheConfig.class, EmployeeService.class})
@ExtendWith(SpringExtension.class)
@EnableCaching
@ImportAutoConfiguration(classes = {
CacheAutoConfiguration.class,
RedisAutoConfiguration.class
})
class EmployeeServiceCachingIntegrationTest {
@MockBean
private EmployeeRepository mockEmployeeRepository;
@Autowired
private EmployeeService employeeService;
@Autowired
private CacheManager cacheManager;
@Test
void
givenRedisCaching_whenFindEmployeeById_thenEmployeeReturnedFromCache() {
Employee employee = new Employee(id, A_DESCRIPTION);
given(mockEmployeeRepository.findById(id))
.willReturn(Optional.of(employee));
Employee employeeNotFromCache = employeeService.getEmployeeById(id);
Employee employeeFromCache = employeeService.getEmployeeById(id);
assertThat(employeeNotFromCache).isEqualTo(employee);
assertThat(employeeFromCache).isEqualTo(employee);
verify(mockEmployeeRepository, times(1)).findById(id);
assertThat(employeeFromCache()).isEqualTo(employee);
}
}从缓存中检索数据
@Cacheable(value = "employeeCache")
public Employee getEmployeeForId(String id) {
return employeeRepository.findById(id)
.orElseThrow(RuntimeException::new);
}我们已经调用了**getEmployeeById()**两次。第一次调用应该从存储库获取项目,而第二次调用应该从缓存返回相同的员工对象,而无需调用存储库。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP