1.实现方法:

1.集成Spring Security框架[里边有登陆成功和失败的监听]

2.集成Redis框架

2.具体实现思路

1.用户输入错误密码登陆失败的监听

@Component
public class LoginLimitFailed implements ApplicationListener<AuthenticationFailureBadCredentialsEvent>{
@Autowired
private SysUserMapper userMapper;
@Autowired
private RedisTemplate redisTemplate;

private final ISysConfigService configService;
@Autowired
public LoginLimitFailed(ISysConfigService configService){
this.configService = configService;
}

@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent authenticationFailureBadCredentialsEvent){
String username = authenticationFailureBadCredentialsEvent.getAuthentication().getPrincipal().toString();
SysUser sysUser = userMapper.selectUserByUserName(username);
Object o = redisTemplate.opsForValue().get(username+"Count");
if(o==null){
redisTemplate.opsForValue().set(username+"Count",0);
}
Object o1 = redisTemplate.opsForValue().get(username+"Count");
long l = Long.parseLong(o1.toString());
l+=1;

redisTemplate.opsForValue().set(username+"Count",l);
if(l==5||l>5){
sysUser.setStatus("1"); //锁定用户
userMapper.updateUser(sysUser);
//一段时间后解锁[在后台设置的参数:单位秒]
new Thread(){
@Override
public void run(){
try{
String keyTime = configService.selectConfigByKey("keyTime");
sleep(Long.parseLong(keyTime)*1000);
sysUser.setStatus("0"); //解锁
userMapper.updateUser(sysUser);
redisTemplate.opsForValue().set(username+"Count",0);
}Catch(Exception e){
e.printStackTrace();
}
}
}.start();
}
System.out.println("这是密码输入的错误次数==>"+l);
}
}

2.用户输入密码成功登陆的监听

@Component
public class LoginLimitSuccess implements ApplicationListener<AuthenticationSuccessEvent>{
@Autowired
private RedisTemplate redisTemplte;
@Override
public void onApplicationEvent(AuthenticationSuccessEvent authenticationSuccessEvent){
Object principal = authenticationSuccessEvent.getAuthentication().getPrincipal();
}
}

3.登陆成功的接口[若依方法的登陆接口,登陆成功后redis缓存账户登陆失败记录次数清零]

@PostMapping("/login")
@ApiOperation("登陆方法")
public Response<TokenDTO> login(@RequestBody LoginBody loginBody){
TokenDTO tokenDTO = new TokenDTO();
String token = "";
if(loginBody.getUsername()!=null && !loginBody.getUsername().equals("")){
token = loginSerive.login(loginBody.getUsername(),loginBody.getPassword(),loginBody.getCode(),loginBody.getUuid());
}else{
token = loginService.login(loginBody.getPhonenumber());
}
tokenDTO.setToken(token);
String username = loginBody.getUsername();
redisTemplate.opsForValue().set(username+"Count",0);
return Response.success(tokenDTO);
}