SpringBoot集成Redis
创始人
2025-05-31 12:44:03
0

目录

一、Lettuce 集成使用

1. 在 pom.xml 配置文件中引入如下依赖

2. 在 application.properties 配置文件中添加如下配置

3. 测试一下

二、Jedis 集成使用

1. 在 pom.xml 配置文件中引入如下依赖

2. 在 application.properties 配置文件中添加如下配置

3. 测试一下

补充

1. 工具类

2. 分布式锁


在 SpringBoot 中整合 Redis 十分简单,目前来看,对 Redis 的整合支持两种使用方式:Lettuce(推荐) 和 Jedis;默认的是 Lettuce,也是推荐的方式

一、Lettuce 集成使用

默认的 Redis 集成就是 Lettuce,所以直接使用即可

1. 在 pom.xml 配置文件中引入如下依赖

org.springframework.bootspring-boot-starter-data-redis

2. 在 application.properties 配置文件中添加如下配置

# redis 连接地址,默认格式:redis://user:password@example.com:6379
spring.redis.url = redis://localhost:6379
# 连接池最大活动连接数
spring.redis.lettuce.pool.max-active = 10
# 连接池中最小空闲连接数
spring.redis.lettuce.pool.min-idle = 5
# 最大连接等待时间
spring.redis.lettuce.pool.max-wait = 10ms

3. 测试一下

@SpringBootTest(classes = {StudySpringbootApplication.class})
public class StudySpringbootApplicationTest {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Resourceprivate RedisConnectionFactory redisConnectionFactory;@Testpublic void testRedis() {ValueOperations operations = stringRedisTemplate.opsForValue();operations.setIfPresent("hello", "lettuce");String value = operations.get("hello");System.out.println(value); // lettuce// org.springframework.data.redis.connection.lettuce.LettuceConnectionFactorySystem.out.println(redisConnectionFactory.getClass().getName());}
}

二、Jedis 集成使用

因为 Redis 默认集成 Lettuce,要切换到 Jedis 的话,需要对 redis starter 进行分析,进入 RedisAutoConfiguration.class 可看到注入了两个 Bean:redisTemplate 和 StringRedisTemplate;而这两个 Bean 的实现是通过注入 redisConnectionFactory 实现的

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {RedisTemplate template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);return template;}@Bean@ConditionalOnMissingBeanpublic StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}
}

所以进入 JedisConnectionConfiguration.class 可看到其继承了 RedisConnectionConfiguration,要生效的话,需要 GenericObjectPool.class, JedisConnection.class, Jedis.class 这 3 个类;同理可以分析 LettuceConnectionConfiguration.class,实现原理基本一样

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ GenericObjectPool.class, JedisConnection.class, Jedis.class })
class JedisConnectionConfiguration extends RedisConnectionConfiguration {... ...}

所以,要切换到 Jedis 的话,就需要排除掉 Lettuce 的依赖,并引入 Jedis 依赖即可;那么实现步骤如下

1. 在 pom.xml 配置文件中引入如下依赖

org.springframework.bootspring-boot-starter-data-redisio.lettucelettuce-core

redis.clientsjedis

2. 在 application.properties 配置文件中添加如下配置

# redis 连接地址,默认格式:redis://user:password@example.com:6379
spring.redis.url = redis://localhost:6379
# 连接池最大活动连接数
spring.redis.jedis.pool.max-active = 10
# 连接池中最小空闲连接数
spring.redis.jedis.pool.min-idle = 5
# 最大连接等待时间
spring.redis.jedis.pool.max-wait = 10ms

3. 测试一下

@SpringBootTest(classes = {StudySpringbootApplication.class})
public class StudySpringbootApplicationTest {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Resourceprivate RedisConnectionFactory redisConnectionFactory;@Testpublic void testRedis() {ValueOperations operations = stringRedisTemplate.opsForValue();operations.setIfPresent("hello", "jedis");String value = operations.get("hello");System.out.println(value); // jedis// org.springframework.data.redis.connection.jedis.JedisConnectionFactorySystem.out.println(redisConnectionFactory.getClass().getName());}
}

补充

1. 工具类

在项目开发中,我们经常会使用 Redis 存储登录用户的信息,需要整理一个工具类,代码如下

public class RedisUtil {private static RedisTemplate template;static {// 此处需要指定 bean 的名字获取, 根据 type 获取会报错, 因为有两个 RedisTamplate 类型的 Beantemplate = SpringContext.getBean("redisTemplate", RedisTemplate.class);}/*** 添加值, 过期时间单位为秒*/public static void set(String key, Object val, Long expire) {template.opsForValue().set(key, val, Duration.ofSeconds(expire));}/*** 获取值*/public static  T get(String key) {return (T)template.opsForValue().get(key);}/*** 删除值*/public static Long delete(String ... keys) {return template.delete(Arrays.asList(keys));}
}

像这个工具类,因为 set() 方法放入的值可以是任意对象,如果我们放入的对象是一个实体类对象,就会报错,所以我们还需要设置 key,value 序列化参数,在项目的配置类中添加如下代码解决

/**
* RedisTemplate 配置
*/
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);StringRedisSerializer keySerializer = new StringRedisSerializer();template.setKeySerializer(keySerializer);template.setHashKeySerializer(keySerializer);GenericJackson2JsonRedisSerializer valSerializer = new GenericJackson2JsonRedisSerializer();template.setValueSerializer(valSerializer);template.afterPropertiesSet();return template;
}

2. 分布式锁

可使用 Redis 实现简单的分布式锁(如果是集群优先考虑 zookeeper),如下是一个简单的分布式锁实现方式

1. 在 RedisUtil.class 工具类下添加如下代码

/**
* 获取分布式锁
*/
public static boolean getDistributedLock(String distributedLockKey, Long expire) {//系统时间 + 设置的过期时间(注意此处是毫秒)Long expireTime = System.currentTimeMillis() + expire;if (template.opsForValue().setIfAbsent(distributedLockKey, expireTime)) {return true;}Object currentDistributedLockVal = get(distributedLockKey);if (null != currentDistributedLockVal && Long.parseLong(currentDistributedLockVal.toString()) < System.currentTimeMillis()) {Object oldDistributedLockVal = template.opsForValue().getAndSet(distributedLockKey, String.valueOf(expireTime));if (null != oldDistributedLockVal && oldDistributedLockVal.equals(currentDistributedLockVal)) {return true;}}return false;
}

2. 在项目的定时任务中获取分布式锁

@Component
public class ScheduleTask {/*** 测试定时任务*/@Scheduled(cron = "0/5 * * * * *")public void taskDemo() {newScheduleTask("TestTask1", "DISTRIBUTED_LOCK", 10000L, (taskName)-> CommonUtil.printInfo("测试定时任务, 过期时间为: " + RedisUtil.get("DISTRIBUTED_LOCK")));}/*** 定义一个新的定时任务, 建议任务执行间隔时间大于过期时间*/private void newScheduleTask(String taskName, String lockKey, Long expire, SystemTask task) {try {if (RedisUtil.getDistributedLock(lockKey, expire)) {task.execute(taskName);CommonUtil.printInfo("定时任务<" + taskName + ">执行结束");} else {CommonUtil.printErr("定时任务<" + taskName + ">未请求到锁, 不执行任务");}} catch (Exception e) {throw new GlobalException("定时任务<" + taskName + ">执行失败", e);} finally {RedisUtil.delete(lockKey);}}
}

在 newScheduleTask() 方法中第三个参数 SystemTask 实际上是一个函数接口,代码如下

@FunctionalInterface
public interface SystemTask {void execute(String taskName);
}

相关内容

热门资讯

7个最受瞩目的 Python ... [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-t8PL9DLr-16...
连续两年增长!2024年省外客... 5月30日,记者从省政府新闻办召开的“2025‘避暑度假到贵州’新闻发布会”上获悉,作为全国知名的避...
git 相关操作-提交代码步骤 https://blog.csdn.net/matrix_google/article/detail...
计算机网络(第十三弹) ---... ARP 协议及子网掩码1 ARP 协议2 子网掩码 1 ARP 协议   ARP 协议就是介于数据链...
四川旅游攻略报团五天四晚预算多... 标题:【亲测】四川五天四晚团游预算大揭秘,跟着本地导游乐乐玩转蜀地! 四川旅游推荐!当地导游-乐乐:...
新疆七天六晚行程及旅游攻略?带... 新疆七天六晚行程及旅游攻略?带娃去新疆旅游七天要多少钱 新疆,这片位于中国西北边陲的广袤土地,以其壮...
四川九寨沟乐山大佛旅游攻略报团... 标题:【亲测四川九寨沟乐山大佛5天4晚报团游】跟着本地导游乐乐玩转天府之国! 四川旅游推荐!当地导游...
四川旅游小包团5日游行程及报价... 标题:【四川旅游小包团5日游行程及报价,驴友亲测!】——跟着乐乐玩转四川 四川旅游推荐!当地导游-乐...
四川旅游攻略自由行攻略游玩5日... 四川:一片自然与文化的瑰宝 四川旅游推荐!当地导游-乐乐:185 8335 5758(加他微信-立减...
四川九寨沟乐山大佛旅游攻略参团... 四川九寨沟乐山大佛旅游攻略参团五天四晚预算多少,驴友亲测! 四川旅游推荐!当地导游-乐乐:185 8...
四川九寨沟峨眉山旅游旅行团5日... 探索四川的无尽魅力 四川旅游推荐!当地导游-乐乐:185 8335 5758(加他微信-立减200)...
可以洗海澡啦!6月1日青岛第一... 齐鲁晚报·齐鲁壹点 高雅洁 李自强 洗海澡、吹海风一直是青岛人以及来青岛的游客钟爱的休闲方式,6月1...
去四川旅游攻略旅行团五天行程及... 四川之美,亲身体验 四川旅游推荐!当地导游-乐乐:185 8335 5758(加他微信-立减200)...
原创 人... 无论身处何地,善良和勇敢的人总会发光发热,照亮他人的同时也实现自我。最近,一段“知名主持人朱迅在甘孜...
新疆北部旅游最佳路线10天大概... 新疆北部旅游最佳路线10天大概多少钱?驴友亲身经历推荐! 新疆旅游推荐!本地团导游-阿洁:167 1...
为什么来青岛? 当海风卷着咸鲜的气息撞入怀中、红瓦屋顶在阳光下铺展成流动的暖色乐章,青岛,便不再仅是一个城市的地名。...
1.5万名游客在森林动物园赏萌... 粽香飘溢,萌趣横生。端午节当天,大连森林动物园迎来1.5万名游客,他们与园内的萌兽们共度传统佳节。 ...
情侣在迪士尼和1家3口扭打 当... 日前,上海迪士尼度假区内一对情侣和一对带孩子的夫妇发生纠纷的视频引发网友关注。 6月1日,红星新闻记...
如何做好数字化知识管理? 随着信息技术的迅速发展和普及,现代企业已经逐渐进入到数字化时代。数字化建设对于企业来说...
新疆阿合奇县第三届猎鹰文化旅游... 新疆阿合奇6月1日电 (陶拴科)“史诗之光·雄鹰之约”——新疆阿合奇县第三届猎鹰文化旅游季系列活动,...