SpringBoot整合Redis

一直都是用别人整合好的项目,所以今天自己整合一下,分享给大家。
首先,下载Redis,如何下载安装可以看菜鸟教程(https://www.runoob.com/redis/redis-install.html)。
RedisDesktopManager不是很好看,我在GitHub上发现了一个超级好看的可视化软件,给大家看一下

image

image

是不是很好看呀,软件下载地址和项目下载地址都在文章末尾,好了,我们开始吧

第一,先搭建一个常规的SpringBoot项目,搭建成功之后引入redis的依赖


     org.springframework.boot
     spring-boot-starter-data-redis
  

第二,我们来配置Redis

# Redis 数据库索引(默认为 0)
spring.redis.database=0
# Redis 服务器地址
spring.redis.host=127.0.0.1
# Redis 服务器连接端口
spring.redis.port=6379
# Redis 服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=50
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.lettuce.pool.max-wait=-1s
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=20
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=10
spring.redis.lettuce.shutdown-timeout=5s`

第三,我们来配置RedisTemplate

@Configuration
@EnableCaching
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        //设置序列化
        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);
        //配置redisTemplate
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        //key序列化
        redisTemplate.setKeySerializer(stringSerializer);
        //value序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        //Hash key序列化
        redisTemplate.setHashKeySerializer(stringSerializer);
        //Hash value序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

第四,我们来写一个Redis的工具类

@Component
public class RedisUtil {

    @Resource
    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 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  T get(final String key, Class clazz) {
        ValueOperations operations = redisTemplate.opsForValue();
        Object obj = operations.get(key);
        if (key != null && obj != null) {
            if (clazz == int.class || clazz == Integer.class) {
                return (T) Integer.valueOf((String) obj);
            } else if (clazz == String.class) {
                return (T) obj;
            } else if (clazz == long.class || clazz == Long.class) {
                return (T) Long.valueOf((String) obj);
            } else {
                return JSON.parseObject((String) obj, clazz);
            }
        }
        return null;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public  boolean set(final String key, T value) {
        boolean result = false;
        try {
            ValueOperations operations = redisTemplate.opsForValue();
            operations.set(key, beanToString(value));
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存,带过期时间
     *
     * @param key
     * @param value
     * @return
     */
    public  boolean set(final String key, T value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations operations = redisTemplate.opsForValue();
            operations.set(key, beanToString(value));
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public  String beanToString(T value) {
        if (value == null) {
            return null;
        }
        Class clazz = value.getClass();
        if (clazz == int.class || clazz == Integer.class) {
            return "" + value;
        } else if (clazz == String.class) {
            return (String) value;
        } else if (clazz == long.class || clazz == Long.class) {
            return "" + value;
        } else {
            return JSON.toJSONString(value);
        }
    }

    /**
     * List集合写入缓存
     */
    public boolean setList(final String key, Object object) {
        boolean result = false;
        try {
            redisTemplate.opsForList().rightPush(key, object);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * List集合写入缓存,带过期时间
     */
    public boolean setList(final String key, Object object, Long expireTime) {
        boolean result = false;
        try {
            redisTemplate.opsForList().rightPush(key, object);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * List集合整个写入缓存
     */
    public boolean setListAll(final String key, List list) {
        boolean result = false;
        try {
            redisTemplate.opsForList().rightPushAll(key, list);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * List集合整个写入缓存,带过期时间
     */
    public boolean setListAll(final String key, List list, Long expireTime) {
        boolean result = false;
        try {
            redisTemplate.opsForList().rightPushAll(key, list);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取List集合
     */
    public List getList(final String key, long start, long end) {
        List result = null;
        result = redisTemplate.opsForList().range(key, start, end);
        return result;
    }

    /**
     * Set集合写入缓存
     */
    public boolean setSet(final String key, Set set) {
        boolean result = false;
        try {
            SetOperations setOperations = redisTemplate.opsForSet();
            for (Object o : set) {
                setOperations.add(key, o);
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean setSet(final String key, Object object) {
        boolean result = false;
        try {
            SetOperations setOperations = redisTemplate.opsForSet();
            setOperations.add(key, object);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Set集合写入缓存,带过期时间
     */
    public boolean setSet(final String key, Object object, Long expireTime) {
        boolean result = false;
        try {
            SetOperations setOperations = redisTemplate.opsForSet();
            setOperations.add(key, object);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public boolean setSet(final String key, Set set, Long expireTime) {
        boolean result = false;
        try {
            SetOperations setOperations = redisTemplate.opsForSet();
            for (Object o : set) {
                setOperations.add(key, o);
            }
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取Set集合
     */
    public Set getSet(final String key) {
        Set result = null;
        result = redisTemplate.opsForSet().members(key);
        return result;
    }

    /**
     * Map集合写入缓存
     */
    public boolean setMap(final String key, Map map) {
        boolean result = false;
        try {
            redisTemplate.opsForHash().putAll(key, map);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Map集合写入缓存,带过期时间
     */
    public boolean setMap(final String key, Map map, Long expireTime) {
        boolean result = false;
        try {
            redisTemplate.opsForHash().putAll(key, map);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 取出Map集合
     */
    public Map getMap(final String key) {
        Map result = null;
        result = redisTemplate.opsForHash().entries(key);
        return result;
    }

    /**
     * 获取自增ID
     */
    public Long incr(String key) {
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = redisAtomicLong.getAndIncrement();
//        if ((null == increment || increment.longValue() == 0) && liveTime > 0) {//初始设置过期时间
//            redisAtomicLong.expire(liveTime, TimeUnit.SECONDS);
//        }
        return increment;
    }
}

第五,在逻辑中使用Redis

List userList = userMapper.getAllUser();
//写入缓存
for(User user:userList){
   redisUtil.set("user_" + user.getName(),user);
}

下载该项目的地址:https://github.com/LordNing97/Springboot-Redis
下载可视化软件的地址:https://download.csdn.net/download/lordning/11473090

你可能感兴趣的:(SpringBoot整合Redis)