学习SpringAOP和作业
This commit is contained in:
@@ -10,20 +10,11 @@ public class Main {
|
||||
// Login 实现了接口,走 JDK 动态代理,Bean 类型是接口,所以用接口取
|
||||
LoginInterface bean = context.getBean(LoginInterface.class);
|
||||
|
||||
// 连续用错密码尝试 5 次
|
||||
for (int i = 0; i < 5; i++) {
|
||||
try {
|
||||
bean.login("admin", "wrongpwd");
|
||||
} catch (Exception e) {
|
||||
// 登录失败抛异常,忽略,继续下一次
|
||||
}
|
||||
bean.login("admin", "wrongpwd");
|
||||
}
|
||||
|
||||
// 最后用正确密码试一次
|
||||
try {
|
||||
bean.login("admin", "123456");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
// bean.login("admin", "123456");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,15 +9,9 @@ import org.springframework.stereotype.Component;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 重试限制切面。
|
||||
* 拦截所有贴了 @Retry 的方法,按用户名统计失败次数。
|
||||
* 失败次数达到上限后,不再执行目标方法,直接拒绝。
|
||||
*/
|
||||
@Component
|
||||
@Aspect
|
||||
public class RetryAspect {
|
||||
|
||||
// 每个用户名已失败次数
|
||||
private final Map<String, Integer> failCount = new HashMap<>();
|
||||
|
||||
@@ -38,7 +32,6 @@ public class RetryAspect {
|
||||
// 执行目标方法,拿到返回值
|
||||
Object result = pjp.proceed();
|
||||
|
||||
// 返回 false 表示登录失败,失败次数 +1
|
||||
if (Boolean.FALSE.equals(result)) {
|
||||
int count = failCount.getOrDefault(username, 0) + 1;
|
||||
failCount.put(username, count);
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.ycjy.ZY.a.dao;
|
||||
|
||||
public class user {
|
||||
private String userName;
|
||||
private String password;
|
||||
private int errorCount;
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public int getErrorCount() {
|
||||
return errorCount;
|
||||
}
|
||||
|
||||
public void setErrorCount(int errorCount) {
|
||||
this.errorCount = errorCount;
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,6 @@ import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 标记方法最多允许重试(失败)多少次。
|
||||
* 用法:@Retry(3) 表示最多失败 3 次,第 4 次拒绝。
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface Retry {
|
||||
|
||||
@@ -14,9 +14,6 @@ public class Login implements LoginInterface {
|
||||
if (username.equals("admin") && pwd.equals("123456")) {
|
||||
System.out.println("login success=====");
|
||||
return true;
|
||||
} else {
|
||||
// 登录失败,返回 false,由切面计数
|
||||
return false;
|
||||
}
|
||||
} else return false;
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user