九、springboot整合redis二之缓冲配置

1.创建Cache配置类

@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport { @Value("${redis.cache.expiration}")
private Long expiration; /**
*
* 管理缓存
*/
@Bean
public CacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(expiration);// 设置缓存默认过期时间(全局的)秒
return cacheManager;
} /**
* 自定义生成的redis key
* 在使用@Cacheable时,如果不指定key,则使用找个默认的key生成器生成的key
* @return
*/
@Bean
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
} @Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
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.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}

2.使用

  1.手动方式:

    Jedis工具类

@Component
public class RedisUtil { private Logger log = LoggerFactory.getLogger(getClass()); @Autowired
private StringRedisTemplate stringRedisTemplate; @Autowired
private RedisTemplate<Object, Object> redisTemplate; /**
* 根据redis key 获取 value
*
* @param key 键
* @return String
*/
public String get(String key) {
return this.stringRedisTemplate.opsForValue().get(key);
} /**
* 根据redis key 设置 value
*
* @param key
* @param value
* @param overwrite
*/
public void set(String key, String value, boolean overwrite) {
if(!overwrite) {//setIfAbsent(key, value):如果key不存在则新增,并返回true;存在则不改变已经有的值,并返回false。
boolean isSet = this.stringRedisTemplate.opsForValue().setIfAbsent(key, value); if (!isSet) {
log.warn("key值已存在且不进行覆写");
} }else {
this.stringRedisTemplate.opsForValue().set(key, value);
}
} /**
* 根据redis key 设置 value 同时设置失效时间
*
* @param key
*/
public void set(String key, String value, long timeout) {
boolean isSet = this.stringRedisTemplate.opsForValue().setIfAbsent(key, value); if (isSet) {
this.stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
} else {
log.warn("key值已存在");
}
} /**
* 根据key检查是否已存在
*
* @param key
* @return boolean
*/
public boolean exists(String key) {
boolean result = false;
result = this.stringRedisTemplate.hasKey(key);
return result;
} /**
* 根据key值删除value
*
* @param key
*/
public void del(String key) {
this.stringRedisTemplate.delete(key);
} /**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return this.redisTemplate.opsForHash().entries(key);
} /**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long timeout) {
try {
this.redisTemplate.opsForHash().putAll(key, map);
if (timeout > 0) {
this.redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 根据key删除hash
*
* @param key
*/
public void delhm(String key) {
this.redisTemplate.delete(key);
} /**
* redis分布式锁(同步锁)
* setIfAbsent(key, value):如果key不存在则新增,并返回true;存在则不改变已经有的值,并返回false。
* 1.第一次key不存在,返回true,并新增key,设置过期时间;
* 2.第二次进来,key存在,返回false说明已经锁了。
* @param key
* @param seconds
* @return boolean
*/
public boolean lock(String key, int seconds) {
log.info("{}开始加锁", key); boolean result = this.stringRedisTemplate.opsForValue().setIfAbsent(key, "LOCKED");
log.info("{}锁定完成-{}", key, result); if(result) {
boolean expired = this.stringRedisTemplate.expire(key, seconds, TimeUnit.SECONDS);
log.info("{}设置过期时间{}-{}", key, seconds, expired);
} return result;
}
}

  2.自动方式:

    添加@Cacheable注解实现缓存添加

    添加@CacheEvict注解实现缓存删除

   具体实现参考上一篇文章:八、springboot整合redis

上一篇:关于react-router: export ‘Switch‘ (imported as ‘Switch‘) was not found in ‘react-router‘报错


下一篇:HTTP返回码总结 (zz)