问题
项目中有时有大量的数据库IO操作,在高并发下会出现数据库的性能瓶颈问题,所以通过搭建数据库缓存来缓解数据库压力。
实现
- 依赖
implementation('org.springframework.boot:spring-boot-starter-cache')
implementation('org.springframework.boot:spring-boot-starter-data-redis')
- 配置Spring Cache
Spring data 2.0+后对Spring cache 部分做了重构,这里采用Spring data 2.0+版本的配置方式。
这里使用了默认过期时间100s,和GenericJackson2JsonRedisSerializer
序列化方式。
针对RedisTemplate存储key出现乱码的问题可通过制定key的序列化工具为StringRedisSerializer
解决。
@EnableCaching
@Configuration
public class SpringCacheConfiguration {
private long duration = 100;
/** RedisCacheManager配置 */
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
Duration expiration = Duration.ofSeconds(duration);
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(expiration)
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())))
.build();
}
}
- 使用Spring Cache注解
在测试发现,直接在MyBatis下的接口上使用会出现SpEL获取值均问null的问题,这里用service对mapper进行包装再加Cache注解。
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@CachePut(value = "rain-cache", key = "'test'")
public void insertUser(User user) {
userMapper.insertUser(user);
}
@CacheEvict(value = "rain-cache", key = "'test'")
public void removeUser(User user) {
userMapper.removeUser(user);
}
@CachePut(value = "rain-cache", key = "'test'")
public void updateUser(User user) {
userMapper.updateUser(user);
}
@Cacheable(value = "rain-cache", key = "'test_' + #name", unless = "#result == null")
public User getUser(String name) {
return userMapper.getUser(name);
}
@Cacheable(value = "rain-cache", key = "'test_' + #id", unless = "#result == null")
public User getUserById(Integer id) {
return userMapper.getUserById(id);
}
@Cacheable(value = "rain-cache", key = "'test_json'", unless = "#result == null")
public JSONObject testJson() {
User user = new User();
user.setAge(11);
user.setCity("CC");
user.setName("xx");
user.setPhone("1283791723");
return JSON.parseObject(JSON.toJSONString(user));
}
}
网友评论