1.1 配置类文件RedisConfig
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
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.*;
import java.time.Duration;
/**
* @Author cw
* @Date 2020/6/18 15:23
* @Description:
*/
@Configuration
@EnableCaching
public class RedisConfig {
private final RedisTemplate redisTemplate;
@Autowired
public RedisConfig(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Bean
public RedisTemplate redisTemplateInit() {
RedisSerializer stringSerialize = redisTemplate.getStringSerializer();
//设置序列化Key的实例化对象
redisTemplate.setKeySerializer(stringSerialize);
redisTemplate.setHashKeySerializer(stringSerialize);
//设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
@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);
// 配置序列化(解决乱码的问题),过期时间30秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
// .entryTtl(Duration.ofSeconds(30))
.entryTtl(Duration.ofSeconds(-1)) //设置过期时间:-1为永久有效
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
注意: CacheManager不配置序列化的情况下在保存对象到redis中时候看到的信息会出现乱码
1.2 配置文件
spring:
redis:
database: xx
host: xxxxxxxxxx
password: xxxxxx
port: xxxx
lettuce:
pool:
max-active: 50
max-idle: 30
min-idle: 30
2.1 方式一 @CachePut
@Override
@CachePut(value = "goods_info",key = "#goodsVo.id")
public GoodsVo insertGoods(GoodsVo goodsVo) {
try{
adminMapper.insertGoods(goodsVo);
// 新增商品维护库存量到缓存(根据情况可忽略)
redisTemplate.opsForValue().set(Tools.GOODS_STOCK_KEY +goodsVo.getId(),goodsVo.getGoodsCount());
return goodsVo;
}catch (Exception e){
e.printStackTrace();
throw new AdminException(ResultCode.ADMIN_INSERT_GOODS_ERROR);
}
}
@CachePut表示不论缓存中是否有记录都执行方法,然后将方法的执行结果保存在缓存中,key为goods_info::id,如下为查看信息事例(注意此处的文件夹并不是hash类型,而是具体到::id为string类型)
2.2 方式二 @Cacheable
@Override
@Cacheable(value = "goods_info",key = "#goodsId")
public GoodsVo selectGoods(Integer goodsId) {
try{
GoodsVo goodsVo = adminMapper.selectGoods(goodsId);
// 新增商品维护库存量到缓存(根据情况可忽略)
redisTemplate.opsForValue().set(Tools.GOODS_STOCK_KEY +goodsVo.getId(),goodsVo.getGoodsCount());
return goodsVo;
}catch (Exception e){
throw new AdminException(ResultCode.ADMIN_OTHER_ERROR);
}
}
@Cacheable表示先去缓存中查找goods_info::id的key对应的value,如何没有则执行方法,并将最后的执行结果保存在缓存中,有的话则直接从缓存中获取。(注意如果是固定key值,则需要在""号中再加个单引号包裹如下)
补充条件:condition满足条件才会进行缓存(例如下)
@Cacheable(value={"users"}, key="#user.id", condition="#user.id%2==0")
public User find(User user) {
return user;
}
2.3 方式三 @CacheEvict
该注解主要用于清除相应的缓存,对应的参数和上面一样有key和condition条件,
allEntries属性默认为false,为true表示清楚对应values值下的所有key
@CacheEvict(value="users", allEntries=true)
public void delete(Integer id) {
System.out.println("delete user by id: " + id);
}
以上为常用,其它注解组合方式可参考文章:https://www.cnblogs.com/fashflying/p/6908028.html
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @author :cw
* @date :Created in 2020/7/22 下午3:06
* @description:
* @modified By:
* @version: $
*/
@Component
public class RedisUtils {
private final RedisTemplate redisTemplate;
@Autowired
public RedisUtils(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 设置普通key value
* @param key
* @param value
*/
public void setKeyValue(String key,String value){
ValueOperations operations = redisTemplate.opsForValue();
operations.set(key,value);
}
/**
* 设置带有失效时间的key value,单位为秒钟
* @param key
* @param value
* @param expireTime
*/
public void setKeyValueWithExpire(String key, Object value, Long expireTime) {
ValueOperations operations = redisTemplate.opsForValue();
operations.set(key, value, expireTime, TimeUnit.SECONDS);
}
/**
* 获取value通过key
* @param key
* @return object对象,不存在则为null
*/
public Object getValueByKey(String key){
ValueOperations operations = redisTemplate.opsForValue();
return operations.get(key);
}
/**
* 删除缓存值 根据key key参数可以为多个
* @param key
* @AddDescription 删除成功返回"1",没有这个key删除则返回"0"
*/
public void delValuesByKey(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
/**
* 增加某个key的数量
* @param key
* @param number
* @Rerutn 新增后的值
*/
public Long incrByKey(String key, Long number) {
return redisTemplate.opsForValue().increment(key, number);
}
/**
* 减少某个key的数量
* @param key
* @param number
* @Rerutn 减少后的值
*/
public Long decrByKey(String key, Long number) {
return redisTemplate.opsForValue().decrement(key, number);
}
/**
* 新增key HashMap中的Item
* @param key
* @param item
* @param value
*/
public void setHMapItem(String key,String item,Object value){
redisTemplate.opsForHash().put(key, item, value);
}
/**
* 新增key HashMap中的Item 并设置HashMap的失效时间
* @param key
* @param item
* @param value
* @param time
* @Description 将替换原有的失效时间 秒
*/
public void setHMapItem(String key,String item,Object value,long time){
redisTemplate.opsForHash().put(key, item, value);
redisTemplate.expire(key,time,TimeUnit.SECONDS);
}
/**
* 设置key HashMap集合
* @param key
* @param map
*/
public void setHMap(String key,Map map){
redisTemplate.opsForHash().putAll(key,map);
}
/**
* 设置key HashMap集合 带有失效时间秒
* @param key
* @param map
* @param time
*/
public void setHMapWithExpire(String key,Map map,long time){
redisTemplate.opsForHash().putAll(key,map);
redisTemplate.expire(key,time,TimeUnit.SECONDS);
}
/**
* 判断hashMap的item字段是否存在
* @param key
* @param item
* @return true or false
*/
public boolean hasHashItem(String key,String item){
return redisTemplate.opsForHash().hasKey(key,item);
}
/**
* 获取HashMap的具体Item的值
* @param key
* @param item
* @return
*/
public Object getHMapItem(String key,String item){
return redisTemplate.opsForHash().get(key,item);
}
/**
* 获取map集合
* @param key
* @return
*/
public Map
补充:具体其他操作根据当前业务环境具体情况进行封装