Redis的配置类以及Redis的操作工具类

懒驴 2021年11月10日 1,776次浏览

SpringBoot集成Redis

1.Maven引入包

<!--Redis整合-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
	<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.9.1</version>
</dependency>

2.Redis的yml配置

#集成Redis
  redis:
    #Redis数据库索引(默认为0)
    database: 0
    #Redis服务器地址
    host: 127.0.0.1
    #Redis服务连接端口
    port: 6379
    #Redis服务连接密码(默认为空)
    password:

    lettuce:
      pool:
        #连接池最大连接数(使用负值表示没有限制)
        max-active: 300
        #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1
        #连接池的最大空闲连接
        max-idle: 10
        #连接池的最小空闲连接
        min-idle: 0
        #连接超时时间(毫秒)
    timeout: 40000

3.Redis的配置类

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/***
 * @Author  懒驴
 * @Title   Redis配置类
 * @Content Redis配置
 **/
@Configuration
public class RedisConfig {

    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(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);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}

4.Redis数据的操作工具类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/***
 * @Author  懒驴
 * @Title   Redis操作工具类
 * @Content Redis操作工具类
 **/
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object>  redisTemplate;        //Redis操作配置类

    //=============================1.常见的键应用 common============================

    /***
     * 1.1.指定缓存失效时间
     * @param key   键
     * @param time  失效时间,秒
     * @return
     */
    public boolean expire(String key, long time){
        try {
            if (time>0){
                this.redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 1.2.根据Key获取过期时间
     * @param key 键 不能为null
     * @return 返回时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key){
        return this.redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /***
     * 1.3.判断Key是否存在
     * @param key 键
     * @return  true 存在, false 不存在
     */
    public boolean hasKey(String key){
        try {
            return this.redisTemplate.hasKey(key);
        }catch (Exception e){
            return false;
        }
    }

    /***
     * 1.4.删除缓存
     * @param key Key 可以传一个值或者多个
     */
    @SuppressWarnings("unchecked")
    public boolean del(String ... key){
        if(null!=key && key.length>0){
            if (key.length==1){
                return this.redisTemplate.delete(key[0]);
            }else{
                long re= this.redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
                if(re>0){
                    return true;
                }else{
                    return false;
                }
            }
        }
        return false;
    }

    //=============================1.常见的键应用 common============================


    //=============================2.字符串类型应用 String============================

    /***
     * 2.1.普通缓存根据Key取信息
     * @param key 键
     * @return  值
     */
    public Object get(String key){
        return key==null ? null : this.redisTemplate.opsForValue().get(key);
    }

    /***
     * 2.2.普通键值缓存放入
     * @param key   键
     * @param value 值
     * @return  true 成功, false 失败
     */
    public boolean set(String key, Object value){
        try{
            this.redisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 2.3.普通键值存放并设置失效时间
     * @param key   键
     * @param value 值
     * @param time  时间(秒),time大于0,如果小于等于0 将设置为无限期
     * @return  true 成功, false 失败
     */
    public boolean set(String key, Object value, long time){
        try {
            if (time>0){
                this.redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            }else{
                set(key, value);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 2.4.递增
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta){
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return this.redisTemplate.opsForValue().increment(key, delta);
    }

    /***
     * 2.5.递减
     * @param key   键
     * @param delta 要减少几(大于0)
     * @return
     */
    public  long decr(String key, long delta){
        if(delta < 0){
            throw new RuntimeException("递减因子必须大于0");
        }
        return this.redisTemplate.opsForValue().increment(key, -delta);
    }

    //=============================2.字符串类型应用 String============================

    //=============================3.Map类型应用 Map=================================

    /***
     * 3.1.HashFet
     * @param key   键 不能为null
     * @param item  项 不能为null
     * @return  值
     */
    public Object hget(String key, String item){
        return this.redisTemplate.opsForHash().get(key, item);
    }

    /***
     * 3.2.获取HashKey对应的所有键值
     * @param key
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key){
        return this.redisTemplate.opsForHash().entries(key);
    }

    /***
     * 3.3.HashSet存值
     * @param key   键
     * @param map   值,对应多个键值
     * @return  true 成功, false 失败
     */
    public boolean hmset(String key, Map<String, Object> map){
        try{
            this.redisTemplate.opsForHash().putAll(key, map);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 3.4.HashSet存值,并设置时间
     * @param key   键
     * @param map   值,对应多个键值
     * @return  true 成功, false 失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time){
        try{
            this.redisTemplate.opsForHash().putAll(key, map);
            if(time>0){
                expire(key,time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 3.5.向一张Hash表中放入数据,如果不存在将创建
     * @param key   键
     * @param item  项
     * @param value 值
     * @return  true 成功, false 失败
     */
    public boolean hset(String key, String item, Object value){
        try {
            this.redisTemplate.opsForHash().put(key, item, value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 3.6.向一张Hash表中放入数据,如果不存在将创建,并设置失效时长
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return  true 成功, false 失败
     */
    public boolean hset(String key, String item, Object value, long time){
        try {
            this.redisTemplate.opsForHash().put(key, item, value);
            if(time>0){
                expire(key, time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 3.7.删除Hash表中的值
     * @param key   键 不能为null
     * @param item  项 可以有多个,不能为空
     */
    public void hdel(String key, Object ... item){
        this.redisTemplate.opsForHash().delete(key, item);
    }

    /***
     * 3.8.判断Hash表中是否有该项的值
     * @param key   键 不能为null
     * @param item  项 不能为null
     * @return  true 存在 ,false不存在
     */
    public boolean hHasKey(String key, String item){
        return this.redisTemplate.opsForHash().hasKey(key, item);
    }

    /***
     * 3.9.hash递增 如果不存在,就会创建一个 并把新增后的值返回
     * @param key   键 不能为null
     * @param item  项 不能为bul
     * @param by    要增加几(大于0)
     * @return
     */
    public double hincr(String key, String item, double by) {
        return this.redisTemplate.opsForHash().increment(key, item, by);
    }

    /***
     * 3.10.Hash递减
     * @param key
     * @param item
     * @param by
     * @return
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    //=============================3.Map类型应用 Map=================================

    //=============================4.Set类型应用 Set=================================

    /***
     * 4.1.根据key获取Set中的所有值
     * @param key  键
     * @return
     */
    public Set<Object> sGet(String key){
        try {
            return this.redisTemplate.opsForSet().members(key);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 4.2.根据value从一个set中查询,是否存在
     * @param key   键
     * @param value 值
     * @return  true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value){
        try {
            return this.redisTemplate.opsForSet().isMember(key, value);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 4.3.将数据放入set缓存
     * @param key   键
     * @param values 值,可以是多个
     * @return
     */
    public long sSet(String key, Object ... values){
        try{
            return this.redisTemplate.opsForSet().add(key, values);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /****
     * 4.4.将数据放入set缓存, 并设置时间
     * @param key   键
     * @param time  时间(秒)
     * @param values    值,可以是多个
     * @return  成功个数
     */
    public long sSet(String key, long time, Object ... values){
        try{
            long count = this.redisTemplate.opsForSet().add(key, values);
            if(time>0){
                expire(key, time);
            }
            return count;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /***
     * 4.5.获取Set缓存的长度
     * @param key  键
     * @return
     */
    public long sGetSetSize(String key){
        try {
            return this.redisTemplate.opsForSet().size(key);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /***
     * 4.6.移除值为Value的Set
     * @param key    键
     * @param values 值,可以是多个
     * @return  移除的个数
     */
    public long setRemove(String key, Object ... values){
        try{
            long count=this.redisTemplate.opsForSet().remove(key, values);
            return count;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }
    //=============================4.Set类型应用 Set=================================

    //=============================5.List类型应用 List=================================

    /***
     * 5.1.获取List缓存的内容
     * @param key   键
     * @param start 开始的下标
     * @param end   结束下标,0到-1代表所以值
     * @return
     */
    public List<Object> listGet(String key, long start, long end){
        try{
            return this.redisTemplate.opsForList().range(key, start, end);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 5.2.获取List缓存的长度
     * @param key  键
     * @return
     */
    public long lGetListSize(String key){
        try{
            return this.redisTemplate.opsForList().size(key);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /***
     * 5.3.通过索引获取List值
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object iGetListIndex(String key, long index){
        try{
            return this.redisTemplate.opsForList().index(key, index);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 5.4.将List放入缓存
     * @param key   键
     * @param value 值
     * @return  true 成功, false 失败
     */
    public boolean listSet(String key, Object value){
        try{
            this.redisTemplate.opsForList().rightPush(key, value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 5.5.将List放入缓存,并设置有效时间
     * @param key   键
     * @param value 值
     * @param time 时间(秒)
     * @return  true 成功, false 失败
     */
    public boolean listSet(String key, Object value, long time){
        try{
            this.redisTemplate.opsForList().rightPush(key, value);
            if(time>0){
                expire(key, time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 5.6.将List放入缓存
     * @param key   键
     * @param value 值
     * @return  true 成功, false 失败
     */
    public boolean listSet(String key, List<Object> value){
        try{
            this.redisTemplate.opsForList().rightPushAll(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 5.7.将List放入缓存,并设置有效时间
     * @param key   键
     * @param value 值
     * @param time 时间(秒)
     * @return  true 成功, false 失败
     */
    public boolean listSet(String key, List<Object> value, long time){
        try{
            this.redisTemplate.opsForList().rightPushAll(key, value);
            if(time>0){
                expire(key, time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 5.8.根据索引修改list中的某条数据
     * @param key
     * @param index
     * @param value
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value){
        try{
            this.redisTemplate.opsForList().set(key, index, value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /***
     * 5.9.移除N个值为value
     * @param key   键
     * @param count 移除的个数
     * @param value 值
     * @return  成功移除的个数
     */
    public long listRemove(String key, long count, Object value){
        try {
            long remove=this.redisTemplate.opsForList().remove(key, count, value);
            return remove;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

}