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_junbiaoredis-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
{@Autowiredprivate RedisProperties redisProperties;/*** Jedis连接池*/@Bean("jedis.pool")@Autowiredpublic 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。*/@Beanpublic KeyGenerator keyGenerator(){return new KeyGenerator(){@Overridepublic 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")@Beanpublic CacheManager cacheManager(RedisConnectionFactory connectionFactory){RedisCacheManager cacheManager = RedisCacheManager.create(connectionFactory);//设置缓存过期时间return cacheManager;}/*** 实例化RedisTemplate对象*/@Beanpublic 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
{@Autowiredprivate 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);
}

执行结果:

源代码下载: https://github.com/kevinpanjunbiao/SpringBootRedis

原文地址:https://blog.csdn.net/pan_junbiao/article/details/111561199

SpringBoot整合Redis并实现Redis工具类相关推荐

  1. springboot整合spring @Cache和Redis

    转载自  springboot整合spring @Cache和Redis spring基于注解的缓存 对于缓存声明,spring的缓存提供了一组java注解: @Cacheable:触发缓存写入. @ ...

  2. SpringBoot 那些自带 Buff 的工具类,你用过几个?

    今日推荐 推荐一个 Java 接口快速开发框架干掉Random:这个类已经成为获取随机数的王者Docker + Intellij IDEA,提升 10 倍生产力!笑出腹肌的注释,都是被代码耽误的诗人! ...

  3. Redis的API调用工具类

    1.一个Redis的工具类!方便调用Redis的API操作! package com.example.demo.utils;import org.springframework.beans.facto ...

  4. SpringBoot整和MinIO以及MinIO工具类

    安装 docker run -p 9000:9000 -p 9090:9090 --net=bridge --name minio -d --restart=always -e "MINIO ...

  5. Memcached的配置,SSH项目中的整合(com.whalin),Memcached工具类,Memcached的代码调用

     1 修改pom.xml,添加依赖文件: <dependency> <groupId>com.whalin</groupId> <artifactId&g ...

  6. SpringBoot中使用Hibernate Validator校验工具类

    1.说明 在Spring Boot已经集成Hibernate Validator校验器的情况下, 对于配置了校验注解的请求参数, 框架会自动校验其参数, 但是如果想手动校验一个加了注解的普通对象, 比 ...

  7. springboot使用 poi 导入导出Excel工具类

    转载的一个比较好用的工具类 import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOE ...

  8. springboot+minio文件上传下载工具类

    引入依赖 <dependency><groupId>io.minio</groupId><artifactId>minio</artifactId ...

  9. SpringBoot项目中如何在静态工具类中使用被Spring容器管理的对象

    在开发的过程中,难免会碰到需要在工具类中使用由spring管理的对象的情况,但是我们都知道,工具类中的静态方法中无法引用spirng容器中的对象(被spring管理的对象不是静态的,静态方法中无法调用 ...

  10. springboot整合哨兵模式连接redis

    在我们的上一篇文章中我们搭建了环境一台服务器上使用docker安装redis6.0.10一主两从以及哨兵模式. 现在我们在这里使用到项目中 创建springboot项目,整合web,swagger2, ...

最新文章

  1. 使用Elasticsearch+filebeat+logstach+kibana构建日志服务平台
  2. aac文件损坏修复软件_SysTools Outlook Recovery Tool : 修复损坏的Outlook PST文件的先进的软件...
  3. 变压器符号_行输出变压器的结构、符号及电路分析
  4. go修改服务器时间,Windows 配置时间同步服务器以及配置时间同步间隔
  5. c# Chart 服务器端动态创建ChartArea
  6. docker 镜像导入导出
  7. 继爱奇艺之后,腾讯视频、优酷宣布:取消剧集超前点播服务
  8. linux探测i2c设备连接状态,手把手教你写Linux I2C设备驱动
  9. SVD在推荐系统中的应用
  10. Shell解析curl返回的json数据
  11. 【图像检索】基于matlab GUI综合颜色和形状特征图像检索【含Matlab源码 395期】
  12. JAVA8 UnaryOperator接口
  13. 手把手教你DIY一款属于自己的万能红外遥控器!
  14. vela和鸿蒙,小米Vela系统发布,将对标华为鸿蒙OS
  15. 计算机软件分类系统软件和,计算机化系统软件分类和验证
  16. mysql启动集群报连接本地失败_Docker的mysql集群节点可以正常创建,但无法正常连接到宿主机的mysql应该如何解决?...
  17. Android apps 拍立知-基于百度Ai的图像识别与tts语音合成(介绍)
  18. flux读取不到数据_WebFlux 中form data获取不到参数问题
  19. maven打包时打包指定的lib文件夹
  20. Unity HybridCLR热更新技术实现

热门文章

  1. 武林外史java游戏,武林外史手游官方版
  2. CNN网络介绍与实践-王者荣耀英雄图片识别
  3. C语言增一减一运算符
  4. 智能化防控,网易云易盾助力中信证券“内容安全”
  5. 兵棋推演系统软件开发方法有哪些呢
  6. 深入理解 LayoutInflater.inflate() 方法
  7. 把这7张思维导图读懂,工作稳当,薪水上涨,前途无量!
  8. 硬盘显示没有初始化找回资料法子
  9. Java剪切图片为圆形,并使边缘透明。
  10. 封装 解封装 网线制作