Redis 是用 C 语言开发的一款开源的、高性能的键值对存储数据库。它采用 BSD 协议,为了适应不同场景下的存储需求,提供了多种键值对类型,到目前为止 Redis 数据库支持5种数据类型,分别是String(字符串)、Hash(哈希)、List(列表)、Set(集合)、Sorted Set(有序集合)。Redis 是目前使用最广泛的内存数据存储系统之一。它支持更丰富的数据结构,支持数据持久化、事务、HA(高可用 High Available)、双机集群系统、主从库。
Redis 是一款功能强大的数据库,在实际应用中,不管是什么框架的网站或系统,都可以将Redis引入项目。下面将介绍使用SpringBoot整合Redis,并实现Redis工具类。
1、SpringBoot整合Redis
(1)创建SpringBoot项目,项目结构如下图:
(2)使用Maven添加依赖文件
在pom.xml配置信息文件中,添加 Redis启动器、Jedis客户端等相关依赖:
<!-- Redis启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!-- 该版本号尽量保持与SpringBoot项目版本号一致 -->
<version>2.4.1</version>
</dependency>
<!-- Jedis客户端依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- SpringBoot/MyBatis整合,包含PageHelper分页控件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.13</version>
</dependency>
<!-- Jackson依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.3</version>
</dependency>
(3)Redis的配置
在 application.yml 配置文件中配置Redis信息:
myenvironment:
user-name: pan_junbiao的博客
blog-url: https://blog.csdn.net/pan_junbiao
redis-project-key: PJB #项目名称,用于区别其他项目的Redis键名
#Spring配置
spring:
#Redis配置
redis:
database: 0 #Redis数据库索引(默认为0)
host: 127.0.0.1 #Redis服务器地址
port: 6379 #Redis服务器连接端口
password: #Redis服务器连接密码(默认为空)
jedis:
pool:
max-active: 8 #连接池最大连接数(使用负值表示没有限制)
max-wait: -1s #连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 8 #连接池中的最大空闲连接
min-idle: 0 #连接池中的最小空闲连接
lettuce:
shutdown-timeout: 100ms #关闭超时时间,默认值100ms
(4)Redis属性类(properties层)
创建 com.pjb.properties 包,并创建 RedisProperties 类(Redis属性类),用于读取 application.yml 文件中的配置项。
package com.pjb.properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.Duration;
/**
* Redis属性类
* @author pan_junbiao
**/
@Component
public class RedisProperties
{
/**
* Redis数据库索引
*/
@Value("${spring.redis.database}")
private int database;
/**
* Redis服务器地址
*/
@Value("${spring.redis.host}")
private String host;
/**
* Redis服务器连接端口
*/
@Value("${spring.redis.port}")
private int port;
/**
* Redis服务器连接密码
*/
@Value("${spring.redis.port}")
private String password;
/**
* 连接池最大连接数
*/
@Value("${spring.redis.jedis.pool.max-active}")
private int maxActive;
/**
* 连接池最大连接数
*/
@Value("${spring.redis.jedis.pool.max-wait}")
private Duration maxWait;
/**
* 连接池中的最大空闲连接
*/
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
/**
* 连接池中的最小空闲连接
*/
@Value("${spring.redis.jedis.pool.min-idle}")
private int minIdle;
public int getDatabase()
{
return database;
}
public void setDatabase(int database)
{
this.database = database;
}
public String getHost()
{
return host;
}
public void setHost(String host)
{
this.host = host;
}
public int getPort()
{
return port;
}
public void setPort(int port)
{
this.port = port;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public int getMaxActive()
{
return maxActive;
}
public void setMaxActive(int maxActive)
{
this.maxActive = maxActive;
}
public Duration getMaxWait()
{
return maxWait;
}
public void setMaxWait(Duration maxWait)
{
this.maxWait = maxWait;
}
public int getMaxIdle()
{
return maxIdle;
}
public void setMaxIdle(int maxIdle)
{
this.maxIdle = maxIdle;
}
public int getMinIdle()
{
return minIdle;
}
public void setMinIdle(int minIdle)
{
this.minIdle = minIdle;
}
}
(5)Redis配置类(config层)
创建 com.pjb.config 包,并创建 RedisConfig 类(Redis配置类),并使用 @Configuration 注解,标注该类为配置类。
package com.pjb.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pjb.properties.RedisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.lang.reflect.Method;
/**
* Redis配置类
* @author pan_junbiao
**/
@Configuration
public class RedisConfig extends CachingConfigurerSupport
{
@Autowired
private RedisProperties redisProperties;
/**
* Jedis连接池
*/
@Bean("jedis.pool")
@Autowired
public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config)
{
return new JedisPool(config, redisProperties.getHost(), redisProperties.getPort());
}
/**
* Jedis连接池配置信息
*/
@Bean(name = "jedis.pool.config")
public JedisPoolConfig jedisPoolConfig()
{
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//连接池最大连接数(使用负值表示没有限制)
jedisPoolConfig.setMaxTotal(redisProperties.getMaxActive());
//连接池最大阻塞等待时间(使用负值表示没有限制)
jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWait().toMillis());
//连接池中的最大空闲连接
jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());
//连接池中的最小空闲连接
jedisPoolConfig.setMinIdle(redisProperties.getMinIdle());
return jedisPoolConfig;
}
/**
* 缓存对象集合中,缓存是以key-value形式保存的,
* 当不指定缓存的key时,SpringBoot会使用keyGenerator生成Key。
*/
@Bean
public KeyGenerator keyGenerator()
{
return new KeyGenerator()
{
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
//类名+方法名
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 缓存管理器
*/
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory)
{
RedisCacheManager cacheManager = RedisCacheManager.create(connectionFactory);
//设置缓存过期时间
return cacheManager;
}
/**
* 实例化RedisTemplate对象
*/
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory)
{
StringRedisTemplate template = new StringRedisTemplate(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);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
(6)Redis异常类(exception层)
创建 com.pjb.exception 包,并创建 RedisException 类(Redis异常类)。
package com.pjb.exception;
/**
* Redis异常类
* @author pan_junbiao
**/
public class RedisException extends Exception
{
public RedisException(String message, Throwable cause)
{
super("Redis服务异常:" + message, cause);
}
public RedisException(String message)
{
super("Redis服务异常:" + message);
}
public RedisException(Throwable cause)
{
super("Redis服务异常:", cause);
}
}
(7)Redis键枚举(common层)
创建 com.pjb.common 包,并创建 RedisKeyEnum 枚举(Redis键枚举)。
package com.pjb.common;
/**
* Redis键枚举
* @author pan_junbiao
**/
public enum RedisKeyEnum
{
USER_INFO //用户信息
}
2、实现Redis工具类
(8)Redis工具类(utils层)
创建 com.pjb.utils 包,并创建 RedisUtils 类(Redis工具类)。
package com.pjb.utils;
import com.pjb.common.RedisKeyEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import com.pjb.exception.RedisException;
import java.util.*;
/**
* Redis工具类
* @author pan_junbiao
**/
@Component
public class RedisUtils
{
@Autowired
private JedisPool jedisPool;
//Redis项目键
@Value("${myenvironment.redis-project-key}")
private String redisProjectKey;
public String getRedisProjectKey()
{
return redisProjectKey;
}
public void setRedisProjectKey(String redisProjectKey)
{
this.redisProjectKey = redisProjectKey;
}
/**
* 获取Jedis对象
* @return
*/
public Jedis getJedis()
{
return jedisPool.getResource();
}
/**
* 释放资源
* @param jedis Jedis对象
*/
public void closeResource(Jedis jedis)
{
if (jedisPool != null && jedis != null)
{
//自Jedis3.0版本后jedisPool.returnResource()遭弃用,
//官方重写了Jedis的close方法用以代替;
jedis.close();
}
}
/**
* 获取Redis键
*/
public String getRedisKey(RedisKeyEnum businessKey)
{
String key = this.redisProjectKey + "_" + businessKey;
return key;
}
/**
* 获取Redis键
*/
public String getRedisKey(RedisKeyEnum businessKey, Object id)
{
String key = String.format("%s_%s::%s",this.redisProjectKey,businessKey,id.toString());
return key;
}
/************************ 字符串(String) *************************/
/**
* 字符串(String)
* 设置字符串值
* @param key 键
* @param value 值
* @return 返回 OK 表示执行成功
*/
public String set(String key, Object value) throws RedisException
{
Jedis jedis = null;
String result = "";
try
{
String valueStr = "";
if (value != null)
{
valueStr = value.toString();
}
jedis = jedisPool.getResource();
result = jedis.set(key, valueStr);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 获取字符串值
* @param key 键
* @return 字符串值
*/
public String get(String key) throws RedisException
{
Jedis jedis = null;
String result = "";
try
{
jedis = jedisPool.getResource();
result = jedis.get(key);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 获取键集合
* @param key 键
* @return 键集合
*/
public Set<String> keys(String key) throws RedisException
{
Jedis jedis = null;
Set<String> result = null;
try
{
jedis = jedisPool.getResource();
result = jedis.keys(key);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 删除字符串键
* @param key 键
* @return true:删除成功;false:删除失败
*/
public boolean del(String key) throws RedisException
{
Jedis jedis = null;
boolean result = false;
try
{
jedis = jedisPool.getResource();
jedis.del(key);
result = true;
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 批量删除所有字符串键
* 支持通配符*号等
* @param key 键
* @return 成功删除字段的数量
*/
public Long delAllByKey(String key) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
jedis = jedisPool.getResource();
Set<String> keySet = jedis.keys(key);
if (keySet != null && keySet.size() > 0)
{
String[] keyArray = keySet.toArray(new String[0]);
result = jedis.del(keyArray);
}
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 返回键所存储的字符串的长度
* @param key 键
* @return 字符串的长度
*/
public Long getStrLen(String key) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
jedis = jedisPool.getResource();
result = jedis.strlen(key);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 判断键是否存在
* @param key 键
* @return true:键存在;false:键不存在
*/
public Boolean exists(String key) throws RedisException
{
Jedis jedis = null;
boolean result = false;
try
{
jedis = jedisPool.getResource();
result = jedis.exists(key);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 查看键的类型
* @param key 键
* @return 键的类型(如:string)
*/
public String type(String key) throws RedisException
{
Jedis jedis = null;
String result = "";
try
{
jedis = jedisPool.getResource();
result = jedis.type(key);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 将键重命名
* @param oldkey 旧键名
* @param newkey 新键名
* @return 返回 OK 表示执行成功
*/
public String rename(String oldkey, String newkey) throws RedisException
{
Jedis jedis = null;
String result = "";
try
{
jedis = jedisPool.getResource();
result = jedis.rename(oldkey, newkey);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 自增1
* @param key 键
* @return 自增后的值
*/
public Long incr(String key) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
jedis = jedisPool.getResource();
result = jedis.incr(key);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 根据增量数,自增
* @param key 键
* @param increment 增量数
* @return 增量后的值
*/
public Long incrBy(String key, long increment) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
jedis = jedisPool.getResource();
result = jedis.incrBy(key, increment);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 递减1
* @param key 键
* @return 递减后的值
*/
public Long decr(String key) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
jedis = jedisPool.getResource();
result = jedis.decr(key);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 根据递减量,递减
* @param key 键
* @param decrement 递减量
* @return 递减后的值
*/
public Long decrBy(String key, long decrement) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
jedis = jedisPool.getResource();
result = jedis.decrBy(key, decrement);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 字符串(String)
* 在键的值的后面拼接字符串
* @param key 键
* @param value 拼接字符串
* @return 拼接字符串后的长度
*/
public Long append(String key, Object value) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
String valueStr = "";
if (value != null)
{
valueStr = value.toString();
}
jedis = jedisPool.getResource();
result = jedis.append(key, valueStr);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/************************ 哈希(Hash) *************************/
/**
* 哈希(Hash)操作:
* 将哈希表 key 中的字段 field 的值设为 value
* @param key 键
* @param field 域
* @param value 值
* @return 如果字段是哈希表中的一个新建字段,并且值设置成功,返回 1 。
* 如果哈希表中域字段已经存在且旧值已被新值覆盖,返回 0 。
*/
public Long hset(String key, String field, Object value) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
String valueStr = "";
if (value != null)
{
valueStr = value.toString();
}
jedis = jedisPool.getResource();
result = jedis.hset(key, field, valueStr);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 哈希(Hash)操作:
* 获取存储在哈希表中指定字段的值
* @param key 键
* @param field 域
* @return 返回给定字段的值。如果给定的字段或 key 不存在时,返回 null 。
* @throws RedisException
*/
public String hget(String key, String field) throws RedisException
{
Jedis jedis = null;
String result = "";
try
{
jedis = jedisPool.getResource();
result = jedis.hget(key, field);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 哈希(Hash)操作:
* 为哈希表 key 中的指定字段的整数值加上增量 increment
* @param key 键
* @param field 域
* @param increment 增量值
* @return 执行 HINCRBY 命令之后,哈希表中字段的值。
*/
public Long hincrBy(String key, String field, long increment) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
jedis = jedisPool.getResource();
result = jedis.hincrBy(key, field, increment);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 哈希(Hash)操作:
* 获取在哈希表中指定 key 的所有字段和值
* @param key 键
* @return 返回哈希表中,所有的字段和值
*/
public Map<String, String> hgetAll(String key) throws RedisException
{
Jedis jedis = null;
Map<String, String> result = null;
try
{
jedis = jedisPool.getResource();
result = jedis.hgetAll(key);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 哈希(Hash)操作:
* 删除一个或多个哈希表字段
* @param key 键
* @param fields 域
* @return 成功删除字段的数量
*/
public Long hdel(String key, String... fields) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
jedis = jedisPool.getResource();
result = jedis.hdel(key,fields);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 哈希(Hash)操作:
* 批量删除所有哈希表字段
* 支持通配符*号等
* @param key 键
* @return 成功删除字段的数量
*/
public Long hdelAllByKey(String key) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
jedis = jedisPool.getResource();
Set<String> keySet = jedis.keys(key);
if (keySet != null && keySet.size() > 0)
{
for (String itemKey : keySet)
{
Map<String, String> fieldMap = jedis.hgetAll(itemKey);
if (fieldMap != null && fieldMap.size() > 0)
{
String[] fieldArray = fieldMap.keySet().toArray(new String[0]);
result += jedis.hdel(itemKey, fieldArray);
}
}
}
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 哈希(Hash)操作:
* 获取哈希表中字段的数量,当key不存在时返回 0
* @param key 键
* @return 哈希表中字段的数量
*/
public Long hlen(String key) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
jedis = jedisPool.getResource();
result = jedis.hlen(key);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 哈希(Hash)操作:
* 获取哈希表中的所有字段名
* @param key 键
* @return 包含哈希表中所有字段的列表。 当 key 不存在时,返回一个空列表。
*/
public Set<String> hkeys(String key) throws RedisException
{
Jedis jedis = null;
Set<String> result = null;
try
{
jedis = jedisPool.getResource();
result = jedis.hkeys(key);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/************************ 集合(Set) *************************/
/**
* 集合(Set)操作:
* 将一个或多个成员元素加入到集合中,
* 已经存在于集合的成员元素将被忽略
* @param key 键
* @param values 值
* @return 被添加到集合中的新元素的数量,不包括被忽略的元素
*/
public Long sadd(String key, Object... values) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
List<String> stringList = new ArrayList<>();
String str = "";
for(Object obj : values)
{
if(obj!=null)
{
str = obj.toString();
}
stringList.add(str);
}
String[] stringArray = stringList.toArray(new String[0]);
jedis = jedisPool.getResource();
result = jedis.sadd(key,stringArray);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 集合(Set)操作:
* 随机返回集合中一个元素
* @param key 键
* @return 随机返回集合中一个元素
*/
public String srandmember(String key) throws RedisException
{
Jedis jedis = null;
String result = "";
try
{
jedis = jedisPool.getResource();
result = jedis.srandmember(key);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/************************ 有序集合(Sorted Set) *************************/
/**
* 有序集合(Sorted Set)
* 向有序集合添加一个或多个成员,或者更新已存在成员的分数
* @param key 键
* @param score 分数
* @param value 值
* @return 被成功添加的新成员的数量,不包括那些被更新的、已经存在的成员。
*/
public Long zadd(String key, double score, Object value) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
String valueStr = "";
if (value != null)
{
valueStr = value.toString();
}
jedis = jedisPool.getResource();
result = jedis.zadd(key, score, valueStr);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 有序集合(Sorted Set)
* 通过索引区间返回有序集合成指定区间内的成员,其中有序集成员按分数值递增(从小到大)顺序排列。
* @param key 键
* @param start 开始索引
* @param end 结束索引
* @return 有序集成员按分数值递增(从小到大)顺序排列
*/
public Set<String> zrange(String key, long start, long end) throws RedisException
{
Jedis jedis = null;
Set<String> result = null;
try
{
jedis = jedisPool.getResource();
result = jedis.zrange(key, start, end);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 有序集合(Sorted Set)
* 通过索引区间返回有序集合成指定区间内的成员,其中有序集成员按分数值递增(从大到小)顺序排列。
* @param key 键
* @param start 开始索引
* @param end 结束索引
* @return 有序集成员按分数值递增(从大到小)顺序排列
*/
public Set<String> zrevrange(String key, long start, long end) throws RedisException
{
Jedis jedis = null;
Set<String> result = null;
try
{
jedis = jedisPool.getResource();
result = jedis.zrevrange(key, start, end);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
/**
* 有序集合(Sorted Set)
* 移除有序集合中给定的排名区间的所有成员
* @param key 键
* @param start 开始索引
* @param stop 结束索引
* @return 被移除成员的数量
*/
public Long zremrangeByRank(String key, long start, long stop) throws RedisException
{
Jedis jedis = null;
long result = 0;
try
{
jedis = jedisPool.getResource();
result = jedis.zremrangeByRank(key, start, stop);
}
catch (Exception ex)
{
throw new RedisException(ex);
}
finally
{
//释放资源
closeResource(jedis);
}
return result;
}
}
3、综合实例
【实例】使用Redis的哈希(Hash)数据类型保存用户信息,然后删除用户信息。
(1)Reids保存用户信息:
/**
* Redis工具类
*/
@Autowired
private RedisUtils redisUtils;
/**
* 使用Redis的哈希(Hash)数据类型,保存用户信息
* @author pan_junbiao
*/
@Test
public void addUserTest() throws RedisException
{
//构建Redis键(格式:PJB_USER_INFO_::用户ID)
String key = redisUtils.getRedisKey(RedisKeyEnum.USER_INFO,1);
//保存到Redis中,使用哈希(Hash)数据类型
redisUtils.hset(key,"userId",1);
redisUtils.hset(key,"userName","pan_junbiao的博客");
redisUtils.hset(key,"blogUrl","https://blog.csdn.net/pan_junbiao");
redisUtils.hset(key,"blogRemark","您好,欢迎访问 pan_junbiao的博客");
//从Redis中读取数据,并打印
System.out.println("用户ID:" + redisUtils.hget(key,"userId"));
System.out.println("用户名称:" + redisUtils.hget(key,"userName"));
System.out.println("博客地址:" + redisUtils.hget(key,"blogUrl"));
System.out.println("博客信息:" + redisUtils.hget(key,"blogRemark"));
}
执行结果:
使用 Redis Desktop Manager(RDM)可视化工具查询缓存数据,如下图:
(2)Redis删除用户信息:
/**
* Redis工具类
*/
@Autowired
private RedisUtils redisUtils;
/**
* 批量删除Redis的哈希(Hash)数据类型
* @author pan_junbiao
*/
@Test
public void delUserTest() throws RedisException
{
//构建Redis键(格式:PJB_USER_INFO_::用户ID)
String key = redisUtils.getRedisKey(RedisKeyEnum.USER_INFO,1);
//批量删除所有哈希表字段
redisUtils.delAllByKey(key);
}
执行结果: