Redis操作工具类

2022/1/19 2:03:46

本文主要是介绍Redis操作工具类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

前期文章中关于RedisOperateUtil工具类使用时需要强制类型转换,针对List等操作不方便,为此特意更新RedisOperateUtil工具类,前文链接:https://blog.csdn.net/liwenyang1992/article/details/111771097?spm=1001.2014.3001.5501

通过Docker搭建Redis环境并启动,命令如下:

#docker启动redis服务
docker run -itd --name redis -p 6379:6379 redis
#使用redis-cli连接redis
docker exec -it redis redis-cli

application.properties配置如下:

server.port=8080
server.servlet.context-path=/redis

############################################################
# REDIS 配置
############################################################
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.lettuce.pool.max-active=18
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.min-idle=2
spring.redis.lettuce.shutdown-timeout=100ms
spring.redis.timeout=100
spring.cache.cache-names=myCache
#是否启用连接池,如果依赖中有common-pools2依赖自动会启用
spring.redis.lettuce.pool.enabled=true

pom.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lwy.it</groupId>
    <artifactId>spring-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-redis</name>
    <description>Demo project for Spring Boot Redis</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- RedisTemplate底层使用commons-pool2来作为连接池-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

由于SpringBoot 2.0版本之后spring-boot-starter-data-redis的底层默认使用了Lettuce来操作redis,早期的版本使用的是Jedis,使用Lettuce获取连接都是通过LettuceConnectionFactory这个工厂类来获取的,默认情况下Lettuce使用的是一个线程安全的共享的本地连接来操作Redis,如果你不希望使用本地连接可以设置shareNativeConnection这个参数为false。备注:RedisTemplate底层使用commons-pool2来作为连接池。

备注:默认情况下RedisTemplate是不使用连接池的,并且性能还是不错的。

RedisConfiguration配置如下:

package com.lwy.it.configuration;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 使用Jackson2JsonRedisSerializer序列化和反序列化
 */
@Configuration
public class RedisConfiguration extends CachingConfigurerSupport {

    @Bean("redisTemplate")
    public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        // 启用连接共享
        lettuceConnectionFactory.setShareNativeConnection(true);
        // 配置连接工厂
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        // 使用Jackson2JsonRedisSerializer来序列化和反序列化Redis的value值
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定药序列化的域,field,get和set,以及修饰符范围
        // ANY任何级别的字段都可以自动识别
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会抛出异常
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        // value采用Json序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // 使用StringRedisSerializer来序列化和反序列化Redis的key
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 使用StringRedisSerializer来序列化和反序列化Redis的Hash key
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // Hash value采用Json序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;
    }

    @Override
    public CacheErrorHandler errorHandler() {
        return new RedisCacheErrorHandler();
    }

}

核心Redis操作工具类RedisOperateUtil如下,主要包括Redis键(Key)、字符串(String)、哈希(Hash)、列表(List)、集合(Set)等常用的操作。

package com.lwy.it.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.QueryTimeoutException;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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

@Component
public final class RedisOperateUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(RedisOperateUtil.class);
    // 默认最长时效时间(秒)
    private static long EXPIRED_TIME = 604800L;

    private void setDefaultExpiredTime(final String key) {
        Long ttl = this.ttl(key, TimeUnit.SECONDS);
        if (!Objects.isNull(ttl) && ttl.equals(-1L)) {
            this.expire(key, EXPIRED_TIME, TimeUnit.SECONDS);
        }
    }

    @Autowired
    private RedisOperations redisTemplate;

    /**
     * DEL key
     *
     * @param key Redis Key
     * @return 是否删除成功
     */
    public Boolean del(final String key) {
        Boolean result = null;
        try {
            result = redisTemplate.delete(key);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * DEL key key
     *
     * @param keys Redis Keys
     * @return 删除的数量
     */
    public Long del(final Set<String> keys) {
        Long result = null;
        try {
            result = redisTemplate.delete(keys);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * EXISTS key
     *
     * @param key Redis Key
     * @return 是否存在key
     */
    public Boolean exists(final String key) {
        Boolean result = null;
        try {
            result = redisTemplate.hasKey(key);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * EXISTS key1 key2
     *
     * @param keys Redis Keys
     * @return 指定为参数的键中存在的键数,多次提及和存在的键被多次计算。
     */
    public Long exists(final Set<String> keys) {
        Long result = null;
        try {
            result = redisTemplate.countExistingKeys(keys);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * EXPIRE key seconds
     *
     * @param key     Redis Key
     * @param timeout 超时时间
     * @param unit    时间粒度单位
     * @return 在管道/事务中使用时为 null
     */
    public Boolean expire(final String key, final long timeout, TimeUnit unit) {
        Boolean result = null;
        try {
            result = redisTemplate.expire(key, timeout, unit);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * TTL key
     *
     * @param key      Redis Key
     * @param timeUnit 时间粒度单位
     * @return 按照给定时间粒度单位,返回过期时间,时间粒度单位为空时默认为秒
     */
    public Long ttl(final String key, TimeUnit timeUnit) {
        if (Objects.isNull(timeUnit)) {
            timeUnit = TimeUnit.SECONDS;
        }
        Long result = null;
        try {
            result = redisTemplate.getExpire(key, timeUnit);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * TTL key
     *
     * @param key Redis Key
     * @return 按照给定时间粒度单位,返回过期时间,时间粒度单位为空时默认为秒
     */
    public Long ttl(final String key) {
        return this.ttl(key, TimeUnit.SECONDS);
    }

    /**
     * SET key value
     *
     * @param key   Redis Key
     * @param value 存储的value
     * @param <V>   value泛型类型
     */
    public <V> void set(final String key, final V value) {
        this.setex(key, value, EXPIRED_TIME, TimeUnit.SECONDS);
    }

    /**
     * GET key
     *
     * @param key Redis Key
     * @param <V> value泛型类型
     * @return 返回存储的value
     */
    public <V> V get(final String key) {
        ValueOperations<String, V> operations = redisTemplate.opsForValue();
        V result = null;
        try {
            result = operations.get(key);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * GETSET key value
     *
     * @param key   Redis Key
     * @param value 存储的value
     * @param <V>   value泛型类型
     * @return 指定key的值,并返回key的旧值
     */
    public <V> V getset(final String key, final V value) {
        ValueOperations<String, V> operations = redisTemplate.opsForValue();
        V result = null;
        try {
            result = operations.getAndSet(key, value);
            this.setDefaultExpiredTime(key);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * MSET key value [key value ...]
     * 缺少过期时间,不建议使用
     *
     * @param map 不能为空
     * @param <V> value泛型类型
     */
    @Deprecated
    public <V> void mset(final Map<String, V> map) {
        if (!CollectionUtils.isEmpty(map)) {
            ValueOperations<String, V> operations = redisTemplate.opsForValue();
            try {
                operations.multiSet(map);
            } catch (Exception exception) {
                LOGGER.error(exception.getMessage(), exception);
            }
        } else {
            LOGGER.warn("Parameters map is null or empty");
        }

    }

    /**
     * MGET key [key ...]
     * 建议使用LinkedHashSet
     *
     * @param keys 不重复Redis Key集合,不能为空
     * @param <V>  value泛型类型
     * @return 结果List集合
     */
    public <V> List<V> mget(final Set<String> keys) {
        List<V> result = Collections.emptyList();
        if (!CollectionUtils.isEmpty(keys)) {
            ValueOperations<String, V> operations = redisTemplate.opsForValue();
            try {
                result = operations.multiGet(keys);
            } catch (RedisConnectionFailureException exception) {
                LOGGER.error(exception.getMessage(), exception);
            } catch (QueryTimeoutException exception) {
                LOGGER.error(exception.getMessage(), exception);
            }
        }
        return result;
    }

    /**
     * SETEX key seconds value
     *
     * @param key     Redis Key
     * @param value   Redis Value
     * @param timeout 超时时间
     * @param unit    单位
     * @param <V>     value泛型类型
     */
    public <V> void setex(final String key, final V value, final long timeout, TimeUnit unit) {
        if (Objects.isNull(unit)) {
            unit = TimeUnit.SECONDS;
        }
        ValueOperations<String, V> operations = redisTemplate.opsForValue();
        try {
            operations.set(key, value, timeout, unit);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
    }

    /**
     * SETNX key value
     *
     * @param key     Redis Key
     * @param value   Redis Value
     * @param timeout 超时时间
     * @param unit    单位
     * @param <V>     value泛型类型
     * @return 设置成功,返回true。设置失败,返回false。
     */
    public <V> Boolean setnx(final String key, final V value, final long timeout, TimeUnit unit) {
        if (Objects.isNull(unit)) {
            unit = TimeUnit.SECONDS;
        }
        ValueOperations<String, V> operations = redisTemplate.opsForValue();
        Boolean result = null;
        try {
            result = operations.setIfAbsent(key, value, timeout, unit);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * INCR key
     * 如果key不存在,那么key的值会先被初始化为0,然后再执行INCR操作。
     * 如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。
     *
     * @param key Redis Key
     * @return 加上1之后,key的值。
     */
    public Long incr(final String key) {
        return this.incrby(key, 1L);
    }

    /**
     * INCRBY key increment
     *
     * @param key   Redis Key
     * @param delta 指定的增量值
     * @return 加上指定的增量值之后,key的值。
     */
    public Long incrby(final String key, final long delta) {
        Long result = null;
        ValueOperations<String, Long> operations = redisTemplate.opsForValue();
        try {
            result = operations.increment(key, delta);
            this.setDefaultExpiredTime(key);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * DECRBY key
     *
     * @param key Redis Key
     * @return 减去1之后,key的值。
     */
    public Long decr(final String key) {
        return this.decrby(key, 1L);
    }

    /**
     * Redis Decrby命令将key所储存的值减去指定的减量值。
     * 如果key不存在,那么key的值会先被初始化为0,然后再执行DECRBY操作。
     * 如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。
     *
     * @param key   Redis Key
     * @param delta 指定减量值
     * @return 减去指定减量值之后,key的值。
     */
    public Long decrby(final String key, final long delta) {
        ValueOperations<String, Long> operations = redisTemplate.opsForValue();
        Long result = null;
        try {
            result = operations.decrement(key, delta);
            this.setDefaultExpiredTime(key);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * HDEL key field [field ...]
     *
     * @param key      Redis Key
     * @param hashKeys Hash Keys
     * @return 被成功删除字段的数量,不包括被忽略的字段。
     */
    public Long hdel(final String key, final String... hashKeys) {
        Long result = null;
        try {
            result = redisTemplate.opsForHash().delete(key, hashKeys);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * HEXISTS key field
     *
     * @param key     Redis Key
     * @param hashKey Hash Key
     * @return 如果哈希表含有给定字段,返回teue。如果哈希表不含有给定字段,或key不存在,返回false。
     */
    public Boolean hexists(final String key, final String hashKey) {
        Boolean result = null;
        try {
            result = redisTemplate.opsForHash().hasKey(key, hashKey);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * HGET key field
     *
     * @param key     Redis Key
     * @param hashKey Hash Key
     * @param <V>     value泛型类型
     * @return 返回给定字段的值。如果给定的字段或key不存在时,返回null。
     */
    public <V> V hget(final String key, final String hashKey) {
        HashOperations<String, String, V> operations = redisTemplate.opsForHash();
        V result = null;
        try {
            result = operations.get(key, hashKey);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * HGETALL key
     *
     * @param key Redis Key
     * @param <V> value泛型类型
     * @return 以列表形式返回哈希表的字段及字段值。若key不存在,返回空列表。
     */
    public <V> Map<String, V> hgetall(final String key) {
        HashOperations<String, String, V> operations = redisTemplate.opsForHash();
        Map<String, V> result = null;
        try {
            result = operations.entries(key);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * HKEYS key
     *
     * @param key Redis Key
     * @return 包含哈希表中所有域(field)列表。当key不存在时,返回一个空列表。
     */
    public Set<String> hkeys(final String key) {
        Set<String> result = null;
        try {
            result = redisTemplate.opsForHash().keys(key);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * HLEN key
     *
     * @param key Redis Key
     * @return 获取哈希表中字段的数量
     */
    public Long hlen(final String key) {
        Long result = null;
        try {
            result = redisTemplate.opsForHash().size(key);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * HMGET key field [field ...]
     * 建议使用LinkedHashSet
     *
     * @param key      Redis Key
     * @param hashKeys Hash Key
     * @param <V>      value泛型类型
     * @return 一个包含多个给定字段关联值的表,表值的排列顺序和指定字段的请求顺序一样。
     */
    public <V> List<V> hmget(final String key, final Set<String> hashKeys) {
        HashOperations<String, String, V> operations = redisTemplate.opsForHash();
        List<V> result = null;
        try {
            result = operations.multiGet(key, hashKeys);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * HSET key field value
     *
     * @param key     Redis Key
     * @param hashKey Hash Key
     * @param value   存储的值
     * @param <V>     value泛型类型
     */
    public <V> void hset(final String key, final String hashKey, final V value) {
        try {
            redisTemplate.opsForHash().put(key, hashKey, value);
            this.setDefaultExpiredTime(key);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
    }

    /**
     * HMSET key field value [field value ...]
     *
     * @param key Redis Key
     * @param map Redis Key Value
     * @param <V> value泛型类型
     */
    public <V> void hmset(final String key, final Map<String, V> map) {
        if (!CollectionUtils.isEmpty(map)) {
            try {
                redisTemplate.opsForHash().putAll(key, map);
                this.setDefaultExpiredTime(key);
            } catch (Exception exception) {
                LOGGER.error(exception.getMessage(), exception);
            }
        }
    }

    /**
     * HSETNX key field value
     * 只有在字段 field 不存在时,设置哈希表字段的值。
     *
     * @param key     Redis Key
     * @param hashKey Hash Key
     * @param value   存储的值
     * @param <V>     value泛型类型
     * @return 设置成功,返回true。如果给定字段已经存在且没有操作被执行,返回false。
     */
    public <V> Boolean hsetnx(final String key, final String hashKey, final V value) {
        Boolean result = null;
        try {
            result = redisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
            this.setDefaultExpiredTime(key);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * HVALS key
     *
     * @param key Redis Key
     * @param <V> value泛型类型
     * @return 一个包含哈希表中所有值的列表。当key不存在时,返回一个空表。
     */
    public <V> List<V> hvals(String key) {
        List<V> result = null;
        try {
            result = redisTemplate.opsForHash().values(key);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * BLPOP key timeout
     *
     * @param key     Redis Key
     * @param timeout 超时时间
     * @param unit    单位
     * @param <V>     value泛型类型
     * @return 被弹出元素的值
     */
    public <V> V blpop(final String key, final long timeout, TimeUnit unit) {
        if (Objects.isNull(unit)) {
            unit = TimeUnit.SECONDS;
        }
        ListOperations<String, V> operations = redisTemplate.opsForList();
        V result = null;
        try {
            result = operations.leftPop(key, timeout, unit);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * BRPOP key timeout
     *
     * @param key     Redis Key
     * @param timeout 超时时间
     * @param unit    单位
     * @param <V>     value泛型类型
     * @return 被弹出元素的值
     */
    public <V> V brpop(final String key, final long timeout, TimeUnit unit) {
        if (Objects.isNull(unit)) {
            unit = TimeUnit.SECONDS;
        }
        ListOperations<String, V> operations = redisTemplate.opsForList();
        V result = null;
        try {
            result = operations.rightPop(key, timeout, unit);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * LINDEX key index
     *
     * @param key   Redis Key
     * @param index 索引
     * @param <V>   value泛型类型
     * @return 通过索引获取列表中的元素
     */
    public <V> V lindex(final String key, final long index) {
        ListOperations<String, V> operations = redisTemplate.opsForList();
        V result = null;
        try {
            result = operations.index(key, index);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * LLEN key
     *
     * @param key Redis Key
     * @return 列表长度
     */
    public Long llen(final String key) {
        Long result = null;
        try {
            result = redisTemplate.opsForList().size(key);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * LPOP key
     *
     * @param key Redis Key
     * @param <V> value泛型类型
     * @return 移出并获取列表的第一个元素
     */
    public <V> V lpop(final String key) {
        ListOperations<String, V> operations = redisTemplate.opsForList();
        V result = null;
        try {
            result = operations.leftPop(key);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * LPUSH key value
     *
     * @param key   Redis Key
     * @param value 存储的值
     * @param <V>   value泛型类型
     * @return 执行LPUSH命令后,列表的长度
     */
    public <V> Long lpush(final String key, final V value) {
        ListOperations<String, V> operations = redisTemplate.opsForList();
        Long result = null;
        try {
            result = operations.leftPush(key, value);
            this.setDefaultExpiredTime(key);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * LPUSH key value [value ...]
     *
     * @param key    Redis Key
     * @param values 存储的列表值
     * @param <V>    value泛型类型
     * @return 执行LPUSH命令后,列表的长度
     */
    public <V> Long lpush(final String key, final Collection<V> values) {
        ListOperations<String, V> operations = redisTemplate.opsForList();
        Long result = null;
        try {
            result = operations.leftPushAll(key, values);
            this.setDefaultExpiredTime(key);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * LRANGE key start stop
     *
     * @param key   Redis Key
     * @param start 开始索引
     * @param end   结束索引
     * @param <V>   value泛型类型
     * @return 列表指定范围内的元素
     */
    public <V> List<V> lrange(final String key, final long start, final long end) {
        ListOperations<String, V> operations = redisTemplate.opsForList();
        List<V> result = null;
        try {
            result = operations.range(key, start, end);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * LSET key index value
     *
     * @param key   Redis Key
     * @param index 索引
     * @param value 存储的值
     * @param <V>   value泛型类型
     */
    public <V> void lset(final String key, final long index, final V value) {
        ListOperations<String, V> operations = redisTemplate.opsForList();
        try {
            operations.set(key, index, value);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
    }

    /**
     * RPOP key
     *
     * @param key Redis Key
     * @param <V> value泛型类型
     * @return 被移除的元素
     */
    public <V> V rpop(final String key) {
        ListOperations<String, V> operations = redisTemplate.opsForList();
        V result = null;
        try {
            result = operations.rightPop(key);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * RPUSH key value
     *
     * @param key   Redis Key
     * @param value 存储的值
     * @param <V>   value泛型类型
     * @return 执行RPUSH操作后,列表的长度
     */
    public <V> Long rpush(final String key, final V value) {
        ListOperations<String, V> operations = redisTemplate.opsForList();
        Long result = null;
        try {
            result = operations.rightPush(key, value);
            this.setDefaultExpiredTime(key);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * RPUSH key value [value ...]
     *
     * @param key    Redis Key
     * @param values 存储的列表值
     * @param <V>    value泛型类型
     * @return 执行RPUSH操作后,列表的长度
     */
    public <V> Long rpush(final String key, Collection<V> values) {
        ListOperations<String, V> operations = redisTemplate.opsForList();
        Long result = null;
        try {
            result = operations.rightPushAll(key, values);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * SADD key member [member ...]
     *
     * @param key    Redis Key
     * @param values 存储的列表值
     * @param <V>    value泛型类型
     * @return 被添加到集合中的新元素的数量,不包括被忽略的元素。
     */
    public <V> Long sadd(final String key, final V... values) {
        SetOperations<String, V> operations = redisTemplate.opsForSet();
        Long result = null;
        try {
            result = operations.add(key, values);
            this.setDefaultExpiredTime(key);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * SCARD key
     *
     * @param key Redis Key
     * @param <V> value泛型类型
     * @return 集合的数量。当集合key不存在时,返回0。
     */
    public <V> Long scard(final String key) {
        Long result = null;
        try {
            result = redisTemplate.opsForSet().size(key);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * SISMEMBER key member
     *
     * @param key    Redis Key
     * @param object 成员元素
     * @return 如果成员元素是集合的成员,返回true。如果成员元素不是集合的成员,或key不存在,返回false。
     */
    public Boolean sismember(final String key, final Object object) {
        Boolean result = null;
        try {
            result = redisTemplate.opsForSet().isMember(key, object);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * SMEMBERS key
     *
     * @param key Redis Key
     * @param <V> value泛型类型
     * @return 集合中的所有成员。
     */
    public <V> Set<V> smembers(final String key) {
        SetOperations<String, V> operations = redisTemplate.opsForSet();
        Set<V> result = null;
        try {
            result = operations.members(key);
        } catch (RedisConnectionFailureException exception) {
            LOGGER.error(exception.getMessage(), exception);
        } catch (QueryTimeoutException exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }

    /**
     * SREM key member [member ...]
     *
     * @param key    Redis Key
     * @param values 删除的值
     * @return 被成功移除的元素的数量,不包括被忽略的元素。
     */
    public Long srem(final String key, final Object... values) {
        Long result = null;
        try {
            result = redisTemplate.opsForSet().remove(key, values);
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
        }
        return result;
    }
}


这篇关于Redis操作工具类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程