Redis 实现 用户输入密码错误5次锁定

/**

* 判断用户账号是否被锁定,及超时时间

*/

@Service

@Slf4j

public class LoginService {

@Resource

private RedisTemplate<String, Object> redisTemplate;

private static final int MAX_LOGIN_ATTEMPTS = 5;

private static final String ACCOUNT_PREFIX = "account:";

private static final String LOCKED_KEY_SUFFIX = ":locked";

private static int LOCK_DURATION_MINUTES = 15;

public boolean validateLogin(String username, boolean flag) {

String accountKey = ACCOUNT_PREFIX + username;

String lockedKey = accountKey + LOCKED_KEY_SUFFIX;

if (redisTemplate.hasKey(lockedKey)) {//判断是否存在锁定账号

// 账号已被锁定,获取过期剩余时间

long unlockTimestamp = redisTemplate.getExpire(lockedKey, TimeUnit.SECONDS);

if (unlockTimestamp>0) {

// 还未解锁,拒绝登录

throw exception(AUTH_LOGIN_USER_LOCK,(unlockTimestamp/60));

} else {

// 解锁时间已过,移除锁定状态

redisTemplate.delete(lockedKey);

}

}

if (!flag) {

// 密码错误

Long loginAttempts = redisTemplate.opsForValue().increment(accountKey, 1);

if (loginAttempts >= MAX_LOGIN_ATTEMPTS) {

// 达到锁定阈值,锁定账号

// 设置 key 为 test 的值,并设置超时时间为 15 分钟

redisTemplate.opsForValue().set(lockedKey, lockedKey, LOCK_DURATION_MINUTES, TimeUnit.MINUTES);

}

return false;

} else {

// 密码正确,重置错误计数器

redisTemplate.delete(accountKey);

return true;

}

}

}

相关推荐
only-qi3 小时前
146. LRU 缓存
java·算法·缓存
阿里小阿希3 小时前
Vue3 + Element Plus 项目中日期时间处理的最佳实践与数据库设计规范
数据库·设计规范
xuxie134 小时前
SpringBoot文件下载(多文件以zip形式,单文件格式不变)
java·spring boot·后端
白鹭4 小时前
MySQL源码部署(rhel7)
数据库·mysql
重生成为编程大王5 小时前
Java中的多态有什么用?
java·后端
666和7775 小时前
Struts2 工作总结
java·数据库
还听珊瑚海吗5 小时前
SpringMVC(一)
数据库
中草药z5 小时前
【Stream API】高效简化集合处理
java·前端·javascript·stream·parallelstream·并行流
野犬寒鸦5 小时前
力扣hot100:搜索二维矩阵 II(常见误区与高效解法详解)(240)
java·数据结构·算法·leetcode·面试
zru_96025 小时前
centos 系统如何安装open jdk 8
java·linux·centos