1、在pom文件中引入Redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、在配置文件中添加redis配置信息
## Redis默认密码是空,此处仅配置
spring:
redis:
host: 127.0.0.1
port: 6379
password:
pool:
# 连接池最大连接数
max-active: 8
# 连接池最大阻塞等待时间
max-wait: -1
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
# 连接超时时间(毫秒)
timeout: 0
3、添加cache配置类
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* 使用TRedisCacheManager作为缓存管理器
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
// redisCacheManager.setDefaultExpiration(6); //设置默认的过期时间
Map<String, Long> map = new HashMap<>();
// 主要针对不同缓存的不同过期时间,结合@Cacheable(value="oauth")使用,但经常会不起作用,建议缓存时再次指定
map.put("oauth", 6L);
redisCacheManager.setExpires(map);
return redisCacheManager;
}
/**
* RedisTemplate配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
// 定义value的序列化方式
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// ObjectMapper类是Jackson库的主要类,用于将Java对象匹配JSON结构
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 如果key是String,需要配置一下StringSerializer,不然key会乱码 /XX/XX
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
4、新建Redis工具类
@SuppressWarnings("unchecked")
@Component
public class RedisComponentUtil<T> {
@SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate;
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
5、自动根据方法生成缓存
@Slf4j
@CacheConfig(cacheNames = "phoneUser")
public abstract class BaseServiceImpl<T, C, M extends BaseMapper<T, C>> implements BaseService<T, C> {
@Autowired
private M mapper;
@CacheEvict(key = "'userCache'")
@Override
public int deleteRecord(Object id) {
log.info("我是从数据库删除记录");
return mapper.deleteRecord(id);
}
@CachePut(key = "'userCache'")
@Override
public void updateRecord(T po) {
log.info("我是从数据库更新数据");
mapper.updateRecord(po);
}
@Cacheable(key = "'userCache'")
@Override
public T selectRecord(C c) {
log.info("我是从数据库查询数据");
return mapper.selectRecord(c);
}
}
/**
* @CacheConfig(cacheNames="phoneUser")注解指的是该类中的缓存的名称是phoneUser
* @CachePut(key="'userCache'")中的userCache要加上''单引号,表示是一个字符串
* @Cacheable能够根据方法的请求参数对起结果进行缓存(缓存的是方法的返回结果),一般用于insert操作
* @CachePut(key="'userCache'")主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和@Cacheable
* 不同的是它每次都会触发真实方法的调用,一般用于update()操作
* @CacheEvict(key="'usercache'")主要针对方法的配置,能够根据一定的条件对缓存进行清空,一般用于delete()操作
*/