springboot使用redis,设置随机过期时间

使用@cacheable的属性中没有设置过期时间的,接下来解决:

1.使用cacheable注解简化缓存操作

     1.1 在pom文件中导入redis依赖 

     1.2 application.yum(springboot的配置文件)中配置redis(直连或哨兵或分片--)

     1.3 按道理 使用cacheable不用写配置类,所以实体类要实现序列化接口,但是由于现在要设置过期时间,所以要写配置类,不实现序列化接口也可以

     1.4 在启动类加注解@EnableCaching

2、可以设置缓存随机过期时间的配置类写法:


import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.time.Duration;
import java.util.Random;

@Configuration
@EnableCaching
public class CacheConfig {

    private static final int MIN_EXPIRY_SECONDS = 300; // 最小过期时间(秒)
    private static final int MAX_EXPIRY_SECONDS = 600; // 最大过期时间(秒)

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        return RedisCacheManager.builder(redisCacheWriter)
                .cacheDefaults(redisCacheConfiguration())
                .build();
    }

    private RedisCacheConfiguration redisCacheConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()))
                .entryTtl(randomExpiry()); // 设置随机过期时间
    }

    private Duration randomExpiry() {
        int expirySeconds = new Random().nextInt((MAX_EXPIRY_SECONDS - MIN_EXPIRY_SECONDS) + 1) + MIN_EXPIRY_SECONDS;
        return Duration.ofSeconds(expirySeconds);
    }
}

3.展示结果

3.1
在这里插入图片描述
在这里插入图片描述

3.2 访问
在这里插入图片描述
在这里插入图片描述
3.3 redis可视化工具查看过期时间
在这里插入图片描述

在这里插入图片描述

好的,我来回答你的问题。首先,我们需要在SpringBoot项目中引入Redis的依赖,可以在pom.xml文件中添加如下代码: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 接下来,我们可以在项目中编写一个验证码的生成工具类,例如: ```java @Component public class VerificationCodeGenerator { private static final String CODES = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final int LENGTH = 6; public String generate() { StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < LENGTH; i++) { sb.append(CODES.charAt(random.nextInt(CODES.length()))); } return sb.toString(); } } ``` 该工具类可以生成一个包含数字和字母的6位验证码。 然后,我们可以在SpringBoot的Controller中编写登录的逻辑,例如: ```java @RestController public class LoginController { @Autowired private StringRedisTemplate redisTemplate; @Autowired private VerificationCodeGenerator verificationCodeGenerator; @PostMapping("/login") public String login(@RequestParam String username, @RequestParam String password, @RequestParam String code) { String key = "verification_code:" + username; String expectedCode = redisTemplate.opsForValue().get(key); if (!code.equals(expectedCode)) { return "验证码错误"; } // 验证码正确,继续登录逻辑 // ... return "登录成功"; } @GetMapping("/verificationCode") public String getVerificationCode(@RequestParam String username) { String code = verificationCodeGenerator.generate(); String key = "verification_code:" + username; redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES); return code; } } ``` 在这个例子中,我们通过一个GET请求获取验证码,将其存入Redis中,并设置过期时间为5分钟。然后,通过一个POST请求进行登录时,我们从Redis中获取到该用户对应的验证码,与用户输入的验证码进行比较,如果一致,则登录成功,否则返回错误信息。 以上就是整合Redis实现使用随机验证码登录的示例,希望对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值