springboot 整合redis 配置

springboot 整合redis 配置

pom.xml文件依赖引入

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--线程池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.29</version>
        </dependency>
        <!--redis 使用加密-->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.15</version>
        </dependency>

redis 序列化 Redis使用FastJson序列化

package com.gremlin.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.util.Assert;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Redis使用FastJson序列化
 * @author admin
 */
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
    
    

    @SuppressWarnings("unused")
    private ObjectMapper objectMapper = new ObjectMapper();

    public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    private Class<T> clazz;

    static {
    
    
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    public FastJson2JsonRedisSerializer(Class<T> clazz) {
    
    
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
    
    
        if (t == null) {
    
    
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
    
    
        if (bytes == null || bytes.length <= 0) {
    
    
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        return JSON.parseObject(str, clazz);
    }

    public void setObjectMapper(ObjectMapper objectMapper) {
    
    
        Assert.notNull(objectMapper, "'objectMapper' must not be null");
        this.objectMapper = objectMapper;
    }

    protected JavaType getJavaType(Class<?> clazz) {
    
    
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}

编写redis 配置类

package com.gremlin.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
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.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: RedisConfig
 * @author: gremlin
 * @version: 1.0.0
 * @description: redis 自定义配置类 因官网给出的redisTemplate不是很好用
 * @date: 2023/4/24 11:28
 */
@Configuration
@Slf4j
public class RedisConfig extends CachingConfigurerSupport {
    
    

    /**
     * @SuppressWarnings 注解用于告诉编译器忽略指定类型的警告信息,value参数指定了要忽略的警告类型.
     * "unchecked"告诉编译器在类型转换时不需要检查泛型的类型安全性,
     * "rawtypes"告诉编译器忽略使用原始类型的警告信息。
     */
    @Bean
    @SuppressWarnings(value = {
    
     "unchecked", "rawtypes" })
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    
    
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        //Json序列化器
        // Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        FastJson2JsonRedisSerializer jackson2JsonRedisSerializer = new FastJson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        //String序列化器
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        //key采用String序列化器
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        //value采用Json序列化器
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 设置过期时间
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(){
    
    
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
        configuration = configuration.serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofHours(2));
        return configuration;
    }

    /**
     * 自定义缓存key生成策略,默认将使用该策略
     */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
    
    
        return (target, method, params) -> {
    
    
            Map<String,Object> container = new HashMap<>(3);
            Class<?> targetClassClass = target.getClass();
            // 类地址
            container.put("class",targetClassClass.toGenericString());
            // 方法名称
            container.put("methodName",method.getName());
            // 包名称
            container.put("package",targetClassClass.getPackage());
            // 参数列表
            for (int i = 0; i < params.length; i++) {
    
    
                container.put(String.valueOf(i),params[i]);
            }
            // 转为JSON字符串
            String jsonString = JSON.toJSONString(container);
            // 做SHA256 Hash计算,得到一个SHA256摘要作为Key
            return DigestUtils.sha256Hex(jsonString);
        };
    }

    @Bean
    @Override
    public CacheErrorHandler errorHandler() {
    
    
        // 异常处理,当Redis发生异常时,打印日志,但是程序正常走
        log.info("初始化 -> [{}]", "Redis CacheErrorHandler");
        return new CacheErrorHandler() {
    
    
            @Override
            public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
    
    
                log.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
            }

            @Override
            public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
    
    
                log.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
            }

            @Override
            public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
    
    
                log.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
            }

            @Override
            public void handleCacheClearError(RuntimeException e, Cache cache) {
    
    
                log.error("Redis occur handleCacheClearError:", e);
            }
        };
    }


    /**
     * Value 序列化
     */
    static class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
    
    

        private Class<T> clazz;

        FastJsonRedisSerializer(Class<T> clazz) {
    
    
            super();
            this.clazz = clazz;
        }

        @Override
        public byte[] serialize(T t) {
    
    
            if (t == null) {
    
    
                return new byte[0];
            }
            return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(StandardCharsets.UTF_8);
        }

        @Override
        public T deserialize(byte[] bytes) {
    
    
            if (bytes == null || bytes.length <= 0) {
    
    
                return null;
            }
            String str = new String(bytes, StandardCharsets.UTF_8);
            return JSON.parseObject(str, clazz);
        }

    }

    /**
     * 重写序列化器
     *
     * @author /
     */
    static class StringRedisSerializer implements RedisSerializer<Object> {
    
    

        private final Charset charset;

        StringRedisSerializer() {
    
    
            this(StandardCharsets.UTF_8);
        }

        private StringRedisSerializer(Charset charset) {
    
    
            Assert.notNull(charset, "Charset must not be null!");
            this.charset = charset;
        }

        @Override
        public String deserialize(byte[] bytes) {
    
    
            return (bytes == null ? null : new String(bytes, charset));
        }

        @Override
        public byte[] serialize(Object object) {
    
    
            String string = JSON.toJSONString(object);
            if (StringUtils.isEmpty(string)) {
    
    
                return null;
            }
            string = string.replace("\"", "");
            return string.getBytes(charset);
        }
    }
}


yal 文件配置

# spring配置
spring:
  redis:
    database: 1  # Redis数据库索引(默认为0)
    host: 127.0.0.1 # Redis服务器地址
    port: 6379 # Redis服务器连接端口
    lettuce:
      pool:
        max-active: 8  # 连接池最大连接数(使用负值表示没有限制) 默认 8
        max-wait: -1   # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
        max-idle: 8    # 连接池中的最大空闲连接 默认 8
        min-idle: 0    # 连接池中的最小空闲连接 默认 0
    connect-timeout: 30000 #连接超时时间(毫秒)
	# enabled: on

编写redis 工具类

package com.gremlin.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.SortParameters;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.query.SortQuery;
import org.springframework.data.redis.core.query.SortQueryBuilder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author gremlin
 * @date 2023/04/25 10:16
 */
@Component
@SuppressWarnings({
    
    "unchecked","all"})
public class RedisUtil {
    
    

    private final RedisTemplate<String,Object> redisTemplate;

    @Autowired
    public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
    
    
        this.redisTemplate = redisTemplate;
    }

    // TODO ************************************ 通用 *******************************

    /**
     * 设置过期时间通过key
     * @param key  键
     * @param time 过期时间 秒
     */
    public Boolean expire(String key, long time) {
    
    
        try {
    
    
            return redisTemplate.expire(key, time, TimeUnit.SECONDS);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置过期时间通过key以及时间类型
     * @param key  键
     * @param time 过期时间 秒
     * @param timeUnit 时间类型
     */
    public Boolean expire(String key, long time,TimeUnit timeUnit) {
    
    
        try {
    
    
            return redisTemplate.expire(key, time, timeUnit);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置在指定时间点过期通过key,true表示设置成功,false表示设置失败或者key不存在
     * @param key  键
     * @param date 指定的过期时间date
     */
    public Boolean expireAt(String key, Date date) {
    
    
        try {
    
    
            return redisTemplate.expireAt(key, date);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据 key 获取过期时间 返回秒
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效 如果键不存在或者已经过期则返回-2
     * 如果键存在并且没有设置过期时间,则返回-1。
     */
    public Long getExpire(String key) {
    
    
        return redisTemplate.getExpire(key);
    }

    /**
     * 根据 key 获取过期时间 返回指定时间类型
     * @param key 键 不能为null
     * @param timeUnit 时间类型
     * @return 时间(秒) 返回0代表为永久有效 如果键不存在或者已经过期则返回-2
     * 如果键存在并且没有设置过期时间,则返回-1。
     */
    public Long getExpire(String key,TimeUnit timeUnit) {
    
    
        return redisTemplate.getExpire(key, timeUnit);
    }

    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在
     */
    public Boolean hasKey(String key) {
    
    
        try {
    
    
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 批量删除缓存 通过key,delete()方法会在删除键时阻塞redis服务器,直到所有被删除的键都被删除为止
     * @param key 可变长参数
     */
    public Boolean delKeys(String... key) {
    
    
        boolean flag = false;
        if (key != null && key.length > 0){
    
    
            if (key.length == 1) {
    
    
                flag = redisTemplate.delete(key[0]);
            } else {
    
    
                List<String> keyList = new ArrayList<>(Arrays.asList(key));
                flag = redisTemplate.delete(keyList) > 0;
            }
        }
        return flag;
    }

    /**
     * 异步批量删除缓存 通过key,unlink() 方法是异步的,因此它不会等待实际删除完成,而是立即返回
     * @param key 可变长参数
     */
    public Boolean unlinkKeys(String... key) {
    
    
        boolean flag = false;
        if (key != null && key.length > 0){
    
    
            if (key.length == 1) {
    
    
                flag = redisTemplate.unlink(key[0]);
            } else {
    
    
                List<String> keyList = new ArrayList<>(Arrays.asList(key));
                flag = redisTemplate.unlink(keyList) > 0;
            }
        }
        return flag;
    }

    /**
     * 获取所有的key
     */
    public Set<String> getKeys(){
    
    
        Set<String> keys = redisTemplate.keys("*");
        return keys;
    }

    /**
     * 获取数据类型
     * @param key
     * @return DataType NONE("none"), STRING("string"), LIST("list"), SET("set"), ZSET("zset"), HASH("hash"),STREAM("stream")
     */
    public DataType getType(String key) {
    
    
        return redisTemplate.type(key);
    }

    /**
     * 重命名键,新的键名已经存在,则会覆盖原来的键。如果原来的键不存在,则会返回一个错误
     * @param oldKey 原来的键名
     * @param newKey 新的键名
     */
    public Boolean rename(String oldKey,String newKey) {
    
    
        try{
    
    
            redisTemplate.rename(oldKey,newKey);
            return true;
        }catch (Exception e){
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 对 Redis 列表、集合或有序集合中的元素进行排序。成果成功返回排序结果。失败,返回 null
     * SortQuery 对象的常用方法
     * by(String pattern):指定排序时的模式。
     * get(String pattern):获取指定模式的元素值。
     * order(SortParameters.Order order):指定排序方式(升序或降序)。
     * limit(long start, long count):指定要排序的元素范围。
     * alphanumeric(boolean alpha):指定是否按照字符串的字母顺序进行排序。
     * @param key 列表、集合或有序集合中的元素进行排序通过键名
     */
    public List<Object> sort(String key) {
    
    
        SortQuery<String> sortQuery = SortQueryBuilder.sort(key)
                .order(SortParameters.Order.ASC)
                .build();
        return redisTemplate.sort(sortQuery);
    }

    /**
     * 重命名键,新的键名已经存在,则不会覆盖原来的键,而是返回一个布尔值 false。
     * @param oldKey 原来的键名
     * @param newKey 新的键名
     */
    public Boolean renameIfAbsent(String oldKey,String newKey) {
    
    
        return redisTemplate.renameIfAbsent(oldKey,newKey);
    }

    /**
     * 查找匹配key
     * @param pattern key
     */
    public List<String> matchKey(String pattern) {
    
    
        ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
        RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
        RedisConnection rc = Objects.requireNonNull(factory).getConnection();
        Cursor<byte[]> cursor = rc.scan(options);
        List<String> result = new ArrayList<>();
        while (cursor.hasNext()) {
    
    
            result.add(new String(cursor.next()));
        }
        try {
    
    
            RedisConnectionUtils.releaseConnection(rc, factory);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 分页查询 key
     * @param patternKey key
     * @param page 页码
     * @param size 每页数目
     */
    public List<String> getKeysForPage(String patternKey, int page, int size) {
    
    
        ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
        RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
        RedisConnection rc = Objects.requireNonNull(factory).getConnection();
        Cursor<byte[]> cursor = rc.scan(options);
        List<String> result = new ArrayList<>(size);
        int tmpIndex = 0;
        int fromIndex = page * size;
        int toIndex = page * size + size;
        while (cursor.hasNext()) {
    
    
            if (tmpIndex >= fromIndex && tmpIndex < toIndex) {
    
    
                result.add(new String(cursor.next()));
                tmpIndex++;
                continue;
            }
            // 获取到满足条件的数据后,就可以退出了
            if(tmpIndex >= toIndex) {
    
    
                break;
            }
            tmpIndex++;
            cursor.next();
        }
        try {
    
    
            RedisConnectionUtils.releaseConnection(rc, factory);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return result;
    }

    // TODO ************************************ String 类型 *******************************

    /**
     * String类型的存入,无过期时间
     * @param key 键
     * @param value 值
     */
    public boolean setString(String key, Object value){
    
    
        try {
    
    
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * String类型的存入,设置过期时间
     * @param key 键
     * @param value 值
     * @param time 过期时间(秒) time要大于0 如果time小于等于0 将设置无限期
     */
    public boolean setString(String key, Object value,long time){
    
    
        try {
    
    
            if (time > 0) {
    
    
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
                return true;
            } else {
    
    
                return setString(key, value);
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * String类型的存入,设置过期时间及时间类型
     * @param key   键
     * @param value 值
     * @param time  时间
     * @param timeUnit 类型 SECONDS MINUTES HOURS DAYS MILLISECONDS MICROSECONDS NANOSECONDS
     */
    public boolean setString(String key, Object value, long time, TimeUnit timeUnit) {
    
    
        try {
    
    
            if (time > 0) {
    
    
                redisTemplate.opsForValue().set(key, value, time, timeUnit);
            } else {
    
    
                setString(key, value);
            }
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * String类型的获取
     * @param key 键
     * @return 返回 value对应的对象
     */
    public Object getString(String key){
    
    
        return key == null || !hasKey(key) ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * String类型批量插入设置 键-值
     * @param key和value的集合
     */
    public Boolean setStringMulti(Map<String,Object> map){
    
    
        try {
    
    
            redisTemplate.opsForValue().multiSet(map);
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * String类型批量插入设置,如果key不存在的话,存在的key不做任何操作,map中的key有一个存在就不做任何操作
     * @param map key和value的集合
     * @return 是否成功
     */
    public Boolean setStringMultiIfAbsent(Map<String,Object> map){
    
    
        try {
    
    
            return redisTemplate.opsForValue().multiSetIfAbsent(map);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * String类型批量获取 值
     * @param keys
     */
    public List<Object> getStringMulti(List<String> keys) {
    
    
        try {
    
    
            return redisTemplate.opsForValue().multiGet(keys);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return Collections.emptyList();
        }

    }

    /**
     * String类型存入 如果key不存在,则设置
     * @param key  key
     * @param value value
     */
    public Boolean setStringIfAbsent(String key,Object value){
    
    
        return redisTemplate.opsForValue().setIfAbsent(key, value);
    }

    /**
     * String类型 给key的值加上delta值
     * @param key key
     * @param delta 参数
     * @return 返回key+delta的值,如果键的值不是整数类型,那么增加操作将抛出异常。
     */
    public Long incrby(String key, long delta){
    
    
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * String类型 给key的值减去delta
     * @param key key
     * @param delta 参数
     * @return 返回key - delta的值,如果键的值不是整数类型,那么增加操作将抛出异常。
     */
    public Long decrby(String key, long delta){
    
    
        return redisTemplate.opsForValue().decrement(key, delta);
    }

    // TODO ************************************ Hash 类型 *******************************

    /**
     * Hash类型存入数据
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功
     */
    public Boolean setHashMap(String key, Map<String, Object> map) {
    
    
        try {
    
    
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Hash类型存入数据,并设置时间
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     */
    public Boolean setHashMap(String key, Map<String, Object> map, long time) {
    
    
        try {
    
    
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
    
    
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Hash类型存入数据,向一张 hash表中放入数据,如果不存在将创建
     * @param key  键
     * @param hashKey hash表的key
     * @param value 值
     */
    public Boolean setHash(String key, String hashKey, Object value) {
    
    
        try {
    
    
            redisTemplate.opsForHash().put(key, hashKey, value);
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

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

    /**
     * Hash类型 获取key下所有的hash值以及hashKey
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> getHashMap(String key) {
    
    
        try {
    
    
            return redisTemplate.opsForHash().entries(key);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Hash类型 获取数据通过key和hash表中数据的key
     * @param key  键 不能为null
     * @param hashKey hash表的key 不能为null
     */
    public Object getHash(String key, String hashKey) {
    
    
        try {
    
    
            return redisTemplate.opsForHash().get(key, hashKey);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Hash类型  判断hash表中是否有该键的值
     * @param key  键 不能为null
     * @param hashKey 项 不能为null
     */
    public Boolean hasHashKey(String key, String hashKey) {
    
    
        try {
    
    
            return redisTemplate.opsForHash().hasKey(key, hashKey);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Hash类型  删除hash表中的值
     * @param key  键 不能为null
     * @param hashKey hash表中的key 可以是多个 不能为null
     * @return 如果删除成功,返回的是被删除字段的数量;如果key不存在,返回0;如果hashKey不存在,也会返回0
     */
    public Long delHash(String key, Object... hashKey) {
    
    
        try {
    
    
            return redisTemplate.opsForHash().delete(key, hashKey);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return 0L;
        }
    }

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

    /**
     * hash递减
     * @param key  键
     * @param hashKey 项
     * @param by  要减少几(小于0)
     */
    public double hdecr(String key, String hashKey, double by) {
    
    
        return redisTemplate.opsForHash().increment(key, hashKey, -by);
    }

    // TODO ************************************ List(LinkedList) 类型 *******************************

    /**
     * List类型 将一个值插入到指定key的列表的末尾(右侧)
     * @param key  键
     * @param value 值
     * @return
     */
    public Boolean setList(String key, Object value) {
    
    
        try {
    
    
            return redisTemplate.opsForList().rightPush(key, value) > 0;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * List类型 将一个值插入到指定key的列表的末尾(右侧),且设置时间
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     */
    public Boolean setList(String key, Object value, long time) {
    
    
        try {
    
    
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
    
    
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * List类型 将一个数组或集合中的所有元素插入到指定key的列表的末尾(右侧)
     * @param key   键
     * @param value 数组或集合
     */
    public Boolean setList(String key, List<Object> value) {
    
    
        try {
    
    
            return redisTemplate.opsForList().rightPushAll(key, value) > 0;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * List类型 将一个数组或集合中的所有元素插入到指定key的列表的末尾(右侧),且设置过期时间
     * @param key   键
     * @param value 数组或集合
     * @param time  时间(秒)
     */
    public Boolean setList(String key, List<Object> value, long time) {
    
    
        try {
    
    
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
    
    
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * List类型 获取list缓存的所有的内容
     * @param key   键
     */
    public List<Object> getList(String key) {
    
    
        try {
    
    
            return redisTemplate.opsForList().range(key, 0, -1);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

    /**
     * List类型 获取list缓存的内容,用来获取Redis中指定key的列表中,
     * 从start到end位置的元素。其中,start和end都是基于0的索引,即第一个元素的索引为0,第二个元素的索引为1
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     * @return 返回一个包含指定范围内元素的List集合
     */
    public List<Object> getList(String key, long start, long end) {
    
    
        try {
    
    
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

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

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

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

    /**
     * List类型 移除与value值相同的多个值
     * @param key   键
     * @param count 删除元素的数量
     * count > 0:从列表的左边开始删除与value相等的元素,直到删除count个元素或者列表为空。
     * count = 0:删除列表中所有与value相等的元素。
     * count < 0:从列表的右边开始删除与value相等的元素,直到删除count个元素或者列表为空。
     * @param value 值
     * @return 移除的个数
     */
    public long delList(String key, long count, Object value) {
    
    
        try {
    
    
            return redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获得锁
     */
    public boolean getLock(String lockId, long second) {
    
    
        Boolean success = redisTemplate.opsForValue().setIfAbsent(lockId, "lock", second, TimeUnit.SECONDS);
        return success != null && success;
    }

    /**
     * 释放锁
     */
    public void releaseLock(String lockId) {
    
    
        redisTemplate.delete(lockId);
    }

    // TODO ************************************ Set 类型 *******************************

    /**
     * Set数据类型 将数据放入set缓存 返回成功个数
     * @param key    键
     * @param values 值 可以是多个
     */
    public long setSet(String key, Object... values) {
    
    
        try {
    
    
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return 0;
        }
    }

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

    /**
     *  Set数据类型  根据key获取Set中的所有值
     * @param key 键
     */
    public Set<Object> getSet(String key) {
    
    
        try {
    
    
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return Collections.EMPTY_SET;
        }
    }

    /**
     * Set数据类型  根据value从一个set中查询,是否存在 判断值是否存在于Set集合中
     * @param key   键
     * @param value 值
     * @return true 存在
     */
    public boolean hasSetValue(String key, Object value) {
    
    
        try {
    
    
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Set数据类型 获取set缓存的长度
     * @param key 键
     * @return
     */
    public long getSetSize(String key) {
    
    
        try {
    
    
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * Set数据类型 移除Set中的某个值
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long delSet(String key, Object... values) {
    
    
        try {
    
    
            return redisTemplate.opsForSet().remove(key, values);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return 0;
        }
    }
}

源码地址
https://gitee.com/fantasy-starry/springboot_redis.git

猜你喜欢

转载自blog.csdn.net/rq12345688/article/details/130504615
今日推荐