在Springboot下使用Jedis操作redis---jedis在代码中的使用

本文介绍如何在Spring Boot项目中使用Jedis操作Redis进行数据缓存。通过重写原有的DAO方法,实现利用Redis存储用户UUID,并介绍了如何通过手机号获取UUID的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇我们完成了jedis的配置,接下来看一下jedis在Springboot中的使用。

首先重新写一下自己项目的Dao文件(service),比如我的项目,UerBean有三个属性,手机号码(telephoneNUmber),密码(password),还有一个就是建立table的时候自动生成的表的唯一标识,uuid。


首先,原来的Dao文件存在着UserDao.java 文件,里面的findUUidByTelephoneNumber 方法,(通过手机号码获得uuid)

public String findUuidByTelephoneNumber(String telephoneNumber)
{
    return (String ) sessionFactory.getCurrentSession().createQuery("select uuid from UserBean where telephoneNumber= :telephoneNumber")
            .setParameter("telephoneNumber", telephoneNumber)
            .uniqueResult();
}

利用jedis来重新写一个class,UserDao_Redis.java

public String findUuidByTelephoneNumber(String telephoneNumber) {

    String key = "User_uuidByTelephone" + telephoneNumber;//前面加入一个前缀,辨认性更强
    String result;

    try {
        shardedJedis = shardedJedisPool.getResource();//在缓存池里取出缓存
        result = shardedJedis.get(key);
        if (result == null) {
            userDao.findUuidByTelephoneNumber(telephoneNumber);
            writeEntryToCacheAndSetExpire(key, result);//在下面后有代码介绍
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException();
    } finally {
        if (shardedJedis != null)
            shardedJedis.close();//记得最后使用完了要关闭幺
    }
    return result;
}
注释:使用try {}catch(){}是确保程序能够运行,

finally{}确保shardedjedis能够返回缓存池(这里并不是吧它给关闭了)详细的可以看一下《Redis的开发和运维》这一本书的java客户端-Jedis(4章2节)

接下来就是writeEntryToCacheAndSetExpire 方法了,顾名思义没就是写一个缓存的入口和设置过期时间。

public void writeEntryToCacheAndSetExpire(String key, String value){

    shardedJedis.set(key, value);
    shardedJedis.expire(key, jedisKeyExpireAfterSecond);
}

还有就是在整个xxDao_Redis.java 下加入他丫,

@Value("${jedis.key.expireAfterSeconds}")
private int jedisKeyExpireAfterSecond;

还有就是常识性的问题:别忘了@Autowired 注入shardedJedispool 呀!


最后,就是Controller层面的代码了,这个没有什么可以讲的,就是把之前的在xxxDao.java的调用方法改为xxxDao_Redis.java的调用方法就好了。

大功告成,赶紧是一下吧

<think>好的,用户让我介绍一下SpringBoot 3.2.0使用Jedis连接Redis。我需要先理清楚这个主题的关键点,确保覆盖配置、依赖、代码示例和常见问题。首先,我应该确认SpringBoot 3.2.0的兼容性,比如对应的Spring版本和Jedis的版本是否匹配。记得用户提到系统级指令,数学公式要用$...$,不过这里可能用不上,但要注意其他格式要求,比如独立公式用$$...$$,不过技术文档可能较少涉及数学公式,但如果有的话要遵守。用户需要中文回答,结构清晰,分步骤解决。 首先,用户可能需要知道为什么选择JedisJedis和Lettuce的区别,比如Jedis是直连,而Lettuce是基于Netty的,但有时候项目可能需要Jedis,比如依赖某些旧库或者特定功能。然后,开始步骤:添加依赖、配置参数、创建配置类、使用JedisClient。需要注意Spring Boot 3.2.0的依赖管理,特别是spring-boot-starter-data-redis默认可能使用Lettuce,所以需要排除掉,并显式引入Jedis。 接下来是具体的依赖项,比如spring-boot-starter-data-redis,排除lettuce-core,然后加入jedisJedis的版本可能需要和Spring Boot兼容,所以可能需要查看Spring Boot 3.2.0的官方文档,确认支持的Jedis版本。例如,可能使用4.4.0或者更高版本。 然后是配置文件application.properties或yml的设置,包括host、port、password、timeout,连接池配置如max-active、max-idle等。这里需要确保配置项的正确性,比如spring.data.redis.host等。 接下来是配置类,使用@Configuration,创建连接工厂JedisConnectionFactory,设置池配置,可能还需要使用@Bean注解。这里可能会有常见的坑,比如忘记设置密码,或者连接池参数配置不当导致连接泄漏。 然后是使用JedisClient,可以通过自动注入StringRedisTemplate或者直接使用JedisPool获取实例。这里需要提醒用户在使用后正确关闭连接,避免资源泄漏。例如在try-with-resources中自动关闭,或者手动jedis.close()。 可能还需要提到一些常见问题,比如连接超时检查防火墙,密码是否正确,Redis服务是否运行,以及连接池配置不当的问题。例如max-active设置过小导致无法获取连接,或者超时时间不够。 此外,需要确保所有代码示例正确,比如Java配置类的注解是否正确,尤其是@Bean的方法是否正确创建JedisConnectionFactory,并传入poolConfig。还要注意Spring Boot的自动配置可能因为引入Jedis而覆盖默认的Lettuce,需要排除依赖。 最后,验证部分,可以通过编写测试用例或者简单的Controller来测试Redis的连接和操作,比如set和get操作,确认是否成功。 可能还需要提醒用户关于版本兼容性,比如Spring Boot 3.2.0是否要求Java 17或更高,Jedis的版本是否适配。例如,Jedis 4.x可能需要Java 8+,而Spring Boot 3.x需要Java 17+,所以没有问题。 总结步骤应该是:添加依赖,配置连接信息,配置连接池,创建配置类,注入使用。同时注意排除不必要的依赖,处理版本问题,以及正确关闭资源。确保回答结构清晰,分步骤说明,每个部分都有代码示例和解释,帮助用户逐步实现。</think>以下是在Spring Boot 3.2.0中使用Jedis连接Redis的详细步骤: --- ### 一、添加依赖 在 `pom.xml` 中排除默认的Lettuce依赖并添加Jedis: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>4.4.0</version> <!-- 与Spring Boot 3.2.0兼容的版本 --> </dependency> ``` --- ### 二、配置Redis连接 在 `application.properties` 中配置: ```properties # Redis基础配置 spring.data.redis.host=127.0.0.1 spring.data.redis.port=6379 spring.data.redis.password=yourpassword spring.data.redis.timeout=5000 # Jedis连接池配置 spring.data.redis.jedis.pool.max-active=8 spring.data.redis.jedis.pool.max-idle=8 spring.data.redis.jedis.pool.min-idle=2 spring.data.redis.jedis.pool.max-wait=2000 ``` --- ### 三、创建配置类 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import redis.clients.jedis.JedisPoolConfig; @Configuration public class RedisConfig { @Bean public JedisPoolConfig jedisPoolConfig() { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxTotal(8); // 最大连接数 poolConfig.setMaxIdle(8); // 最大空闲连接 poolConfig.setMinIdle(2); // 最小空闲连接 poolConfig.setMaxWaitMillis(2000); // 最大等待时间(ms) return poolConfig; } @Bean public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig poolConfig) { JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setHostName("127.0.0.1"); factory.setPort(6379); factory.setPassword("yourpassword"); factory.setTimeout(5000); // 超时时间 factory.setPoolConfig(poolConfig); // 注入连接池配置 return factory; } } ``` --- ### 四、使用Jedis操作Redis #### 方式1:通过 `StringRedisTemplate` ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; @Component public class RedisService { @Autowired private StringRedisTemplate stringRedisTemplate; public void setKey(String key, String value) { stringRedisTemplate.opsForValue().set(key, value); } public String getKey(String key) { return stringRedisTemplate.opsForValue().get(key); } } ``` #### 方式2:直接通过 `Jedis` 实例 ```java import redis.clients.jedis.Jedis; import javax.annotation.PostConstruct; @Component public class JedisDemo { private Jedis jedis; @PostConstruct public void init() { jedis = new Jedis("127.0.0.1", 6379); jedis.auth("yourpassword"); } public void executeCommand() { jedis.set("demoKey", "Hello Jedis"); System.out.println(jedis.get("demoKey")); jedis.close(); // 需手动关闭连接 } } ``` --- ### 五、常见问题排查 1. **连接超时** - 检查防火墙是否开放Redis端口 - 确认Redis配置中 `bind 0.0.0.0` 和 `protected-mode no` 2. **认证失败** - 检查 `spring.data.redis.password` 是否与Redis服务器的 `requirepass` 配置一致 3. **连接池耗尽** - 调整 `max-active` 参数或检查是否有未释放的连接 --- ### 六、版本兼容性说明 - Spring Boot 3.2.0 需要 **Java 17+** - Jedis 4.x 兼容 Redis 6.x/7.x 协议 - 生产环境建议通过 `@ConfigurationProperties` 解耦配置 通过以上步骤即可在Spring Boot 3.2.0中安全使用Jedis操作Redis
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值