【redis|SpringBoot缓存使用Redis与@CaChe注解整合 简洁使用】?
一、配置
1.引入redis jar包
org.springframework.boot
spring-boot-starter-data-redis
2.springboot集成redis写配置,application.properties
spring:
redis:
database: 0 # Database index used by the connection factory.
url: redis://user:@127.0.0.1:6379 # Connection URL. Overrides host, port, and password. User is ignored. Example: redis://user:password@example.com:6379
host: 127.0.0.1 # Redis server host.
password: # Login password of the redis server.
port: 6379 # Redis server port.
ssl: false # Whether to enable SSL support.
timeout: 5000 # Connection timeout.
3.编写配置类 RedisCacheConfig.java
package xx;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate<>();
RedisSerializer redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题),过期时间600秒
RedisCacheConfiguration config = RedisCacheConfiguration
.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600)).serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
// 可以给每个cacheName不同的RedisCacheConfiguration设置不同的过期时间
//.withCacheConfiguration("Users",config.entryTtl(Duration.ofSeconds(100)))
.transactionAware()
.build();
return cacheManager;
}}
二、使用
在启动类加上开启缓存的注解 @EnableCaching , 其它注解写在业务层
1.写入缓存@CachePut
文章图片
代码说明:将系统code实体类放入缓存为systemIdCache中,key为系统编码,状态为1时新增
/**新增与更新数据**/
@Override
@CachePut(value = "https://www.it610.com/article/systemIdCache", key = "#record.sysCode", condition = "#result.status eq 1")
public SystemIdDto insertAndUpdateSelective(SystemIdDto record){
systemIdDao.insertAndUpdateSelective(record);
return record;
}
2.读取缓存@Cacheable
文章图片
代码说明:读取存储名称为
systemIdCache
,key为sysCode
值的数据,查找不到时,将会执行此查询方法,再将查询出的数据存入缓存中/**根据系统code查询*/
@Override
@Cacheable(value = "https://www.it610.com/article/systemIdCache",key = "#sysCode")
public SystemIdDto selectBySysCode(String sysCode) {
SystemIdDto dto = new SystemIdDto();
dto.setSysCode(sysCode);
dto.setStatus(SystemIdDto.Status.YouXiao);
SystemIdDto dto = systemIdDao.selectBySysCode(dto);
return dto ;
}
3.删除缓存@CacheEvict
文章图片
代码说明:方法代码写的是逻辑删除,修改状态为无效,注解
@CacheEvice
删除sysCode
为key的缓存,且在这个方法执行前删除/**根据主键删除**/
@Override
@CacheEvict(value="https://www.it610.com/article/systemIdCache",key = "#record.sysCode", beforeInvocation=true)
public CommonResp deleteById(SystemIdDto record){
record.setStatus(SystemIdDto.Status.WuXiao);
systemIdDao.updateById(record);
return CommonRespBuild.Success;
}
4.注解配置新增/读取/删除 例子中 所有注解的@CacheConfig
value
属性都是同一个,为了方便,我们可以将它提取出来。 /**使用@CacheConfig注解将公共提取出来,
*整个类的cache注解都公用这个属性,
*其他方法不使用仍可覆盖*/
@Service
@CacheConfig(cacheNames = "systemIdCache")
public class SystemIdServiceImpl implements SystemIdService { /**根据系统code查询*/
//公用缓存名称
@Override
@Cacheable(key = "#sysCode")
public SystemIdDto selectBySysCode(String sysCode) {
SystemIdDto dto = new SystemIdDto();
dto.setSysCode(sysCode);
dto.setStatus(SystemIdDto.Status.YouXiao);
SystemIdDto dto = systemIdDao.selectBySysCode(dto);
return dto ;
}/**根据主键删除**/
//不使用公用缓存名称
@Override
@CacheEvict(value="https://www.it610.com/article/systemIdCache1",key = "#record.sysCode", beforeInvocation=true)
public CommonResp deleteById(SystemIdDto record){
record.setStatus(SystemIdDto.Status.WuXiao);
systemIdDao.updateById(record);
return CommonRespBuild.Success;
}
}
?
推荐阅读
- java|SpringCloud笔记一( 跨模块调用,服务注册发现(Eureka、Nacos))
- redis|springboot整合spring @Cache和Redis
- Spring|[01] 使用IDEA搭建SpringCloud项目方法_简单入门
- 笔记|Redis-redis概念、配置、Sentinel高可用
- SSM|一、Spring MVC 简介
- Java|SpringMVC 的入门
- Redis集群搭建方式
- redis|centos7 redis集群搭建
- redis|redis集群搭建之主从复制