SpringBoot集成redis的使用以及使用记录分析

一、快速集成及注意事项

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类型)
SpringBoot集成redis的使用以及使用记录分析_第1张图片
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值,则需要在""号中再加个单引号包裹如下)
SpringBoot集成redis的使用以及使用记录分析_第2张图片
补充条件: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

三、RedisUtils的常用操作封装

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 getHMap(String key){
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 原子操作新增hashMap的item的数值
     * @param key
     * @param item
     * @param num
     * @return 新增后的数值
     */
    public Long hMapItemIncr(String key,String item,Long num){
        return redisTemplate.opsForHash().increment(key,item,num);
    }

    /**
     * 原子操作减少hashMap的item的数值
     * @param key
     * @param item
     * @param num
     * @return 减少后的数值
     */
    public Long hMapItemDecr(String key,String item,Long num){
        return redisTemplate.opsForHash().increment(key,item,-num);
    }

    /**
     * 向zSet中增加成员
     * @param key
     * @param value
     * @param score
     */
    public void zSetAdd(String key, Object value, Double score) {
        redisTemplate.opsForZSet().add(key, value, score);
    }

    /**
     * 向zSet(有序集合)中增加多个信息
     * @param key
     * @param sets
     * @Return 返回成功新增的个数
     */
    public Long zSetAddMore(String key, Set> sets) {
        return redisTemplate.opsForZSet().add(key, sets);
    }

    /**
     * 增加zSet(有序集合)中具体value增加数值
     * @param key
     * @param value
     * @param num
     */
    public void zSetIncrementScore(String key, Object value, Long num) {
        redisTemplate.opsForZSet().incrementScore(key, value, num);
    }

    /**
     * 获取该value在key(有序集合)中的排名
     * @param key key
     * @param value value
     * @return long
     */
    public Long zSetReverseRank(String key, Object value) {
        Long rank = redisTemplate.opsForZSet().reverseRank(key, value);
        if (rank == null) {
            return null;
        }
        return rank + 1;
    }

    /**
     * 获取该set(有序集合)中的排名数据
     * @param key key
     * @return set
     */
    public Set zSetReverseRange(String key, long start, long end) {
        return redisTemplate.opsForZSet().reverseRange(key, start, end);
    }

    /**
     * 将多个值数组加入到set中(无序)
     * @param key
     * @param value
     * @return 新增成功的个数
     */
    public Long setAddMore(String key, Object... value) {
        return redisTemplate.opsForSet().add(key, value);
    }

    /**
     * 从set中随机删除一个
     * @param key
     * @return
     */
    public Object setPop(String key) {
        return redisTemplate.opsForSet().pop(key);
    }

    /**
     * list队列中从左加入一个值
     * @param key
     * @param value
     */
    public Long listAddOne(String key, Object value) {
        return redisTemplate.opsForList().leftPush(key, value);
    }

    /**
     * list队列将多个值(数组)从左加入队列
     * @param key
     * @param arr
     */
    public void listAddMore(String key, Object... arr) {
        redisTemplate.opsForList().leftPushAll(key, arr);
    }

    /**
     * 获取list的集合所有值根据 key
     * @param key
     */
    public List listGetAll(String key) {
        return redisTemplate.opsForList().range(key, 0L, -1L);
    }

    /**
     * 右出队一个数据并设置原失效时间 秒
     * @param key
     * @param number
     * @return
     */
    public Object listPopMore(String key, Long number) {
        return redisTemplate.opsForList().rightPop(key, number, TimeUnit.SECONDS);
    }

    /**
     * 右边出队一个数据
     * @param key
     * @return
     */
    public Object listRightPopOne(String key) {
        return redisTemplate.opsForList().rightPop(key);
    }
}

补充:具体其他操作根据当前业务环境具体情况进行封装

你可能感兴趣的:(#,redis,springBoot,中间件技术,java,redis,缓存,springBoot)