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

目录

一、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);
}

相关内容

热门资讯

从南昌机场/火车站到庐山最全交... 从南昌机场/火车站到庐山最全交通攻略:直达大巴?先到九江?一篇讲清! 从南昌机场或火车站出来,拖着行...
梅岭山上值得住的民宿推荐:在山... 梅岭山上值得住的民宿推荐:在山中民宿住一晚,才是打开梅岭的正确方式 想在梅岭住一晚,这个想法太棒了!...
知名奶茶紧急致歉:下架! 近日,有多名网友发帖称知名奶茶品牌乐乐茶的新品“苹果糖”不好喝:“一口下去牙冠都要被粘下来了。” ...
这道家常红烧肉,装着妈妈的故事... 那行,咱们开始聊聊跟美食有关的故事。美食可不是仅仅味道简单拼凑,它背后有人的记忆相互交织,有地域的风...
周二非洲杯焦点战:卫冕冠军塞内... 非洲杯小组赛再燃战火!北京时间周二晚间,一场备受瞩目的对决即将上演——卫冕冠军塞内加尔强势亮相,对阵...