Spring boot攔截器實現(xiàn)IP黑名單的完整步驟
一·業(yè)務場景和需要實現(xiàn)的功能
以redis作為IP存儲地址實現(xiàn)。
業(yè)務場景:針對秒殺活動或者常規(guī)電商業(yè)務場景等,防止惡意腳本不停的刷接口。
實現(xiàn)功能:寫一個攔截器攔截掉黑名單IP,額外增加一個接口,將ip地址添加到redis中,并且返回redis中當前全部ip
二·Springboot中定義一個攔截器
@Order(0)
@Aspect
@Component
public class AopInterceptor {
/**
* 定義攔截器規(guī)則
*/
@Pointcut("execution(* com.test.test.api.controller.test.test.*(..))")
public void pointCut() {
}
/**
* 攔截器具體實現(xiàn)
*
* @throws Throwable
*/
@Around(value = "pointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//判斷是否為黑名單用戶
String ip = getIpAddress(request);
if (checkIpBlack(ip)) {
//ip在黑名單中返回false
//return false;
DefaultResponse defaultResponse = new DefaultResponse();
defaultResponse.setCode(-1);
defaultResponse.setMessage("ip在黑名單中,拒絕訪問.");
SysLogHelper.log("IpBlackAopInterceptor", "當前請求ip" + ip, "ip在黑名單中,拒絕訪問");
return defaultResponse;
} else {
//ip不在黑名單中返回true
SysLogHelper.log("IpBlackAopInterceptor", "當前請求ip" + ip, "ip正常,允許訪問");
return point.proceed();
}
} catch (Exception e) {
e.printStackTrace();
SysLogHelper.error("IpBlackAopInterceptor黑名單攔截異常:", ExceptionUtils.getMessage(e) + "詳細" + ExceptionUtils.getStackTrace(e), null);
}
return point.getArgs();
}
//對比當前請求IP是否在黑名單中,注意(對比黑名單ip存放在redis中)
public boolean checkIpBlack(String ip) throws Exception {
IpBlackBody body = new IpBlackBody();
body = cacheHelper.get("IpBlack:ips", IpBlackBody.class);
if (body != null) {
for (int i = 0; i < body.getIp().length; i++) {
if (body.getIp()[i].equals(ip))
return true;
}
}
return false;
}
}
三·獲取請求主機IP地址
public final static String getIpAddress(HttpServletRequest request)
throws IOException {
// 獲取請求主機IP地址,如果通過代理進來,則透過防火墻獲取真實IP地址
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0
|| "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (int index = 0; index < ips.length; index++) {
String strIp = (String) ips[index];
if (!("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
return ip;
}
四·擴展接口,實現(xiàn)將黑名單IP寫入redis當中,并返回當前所有黑名單IP
@RestController
public class IpBlackController {
@Autowired(required = false)
private CacheHelper cacheHelper;
@PostMapping("/testIpBlack")
public IpBlackBody IpBlack(@RequestBody IpBlackBody ipBlackBody) throws Exception {
IpBlackBody body = new IpBlackBody();
body = cacheHelper.get("IpBlack:ips", IpBlackBody.class);
if (body != null) {
//拼接當前IP與redis中現(xiàn)有ip
linkArray(body.getIp(), ipBlackBody.getIp());
//將數(shù)據(jù)賦給body
body.setIp(linkArray(body.getIp(), ipBlackBody.getIp()));
//setex中第二個參數(shù)時間為S,根據(jù)業(yè)務場景相應調整,此處我設置為一天
//將body中拼接后的ip地址數(shù)據(jù)寫入redis中
cacheHelper.setex("IpBlack:ips", 86400, body);
} else {
cacheHelper.setex("IpBlack:ips", 86400, ipBlackBody);
body = cacheHelper.get("IpBlack:ips", IpBlackBody.class);
return body;
}
return body;
}
//拼接兩個String[]的方法
public static String[] linkArray(String[] array1, String[] array2) {
List<String> list = new ArrayList<>();
if (array1 == null) {
return array2;
}
if (array2 == null) {
return array1;
}
for (int i = 0; i < array1.length; i++) {
list.add(array1[i]);
}
for (int i = 0; i < array2.length; i++) {
list.add(array2[i]);
}
String[] returnValue = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
returnValue[i] = list.get(i);
}
return returnValue;
}
}
總結:
首先根據(jù)需要攔截的controller攔截響應請求controller層,然后根據(jù)編寫相關攔截器的具體實現(xiàn),其中包含兩部主要操作:
1.獲取到遠程請求主機的實際ip地址
2.對比當前ip是否在黑名單中(此次操作需要讀取redis中的黑名單ip列表)
然后根據(jù)當前需求增加了一個redis接口,實現(xiàn)將需要封禁的IP地址增加到redis黑名單中并返回當前所有的黑名單IP地址。
至此:至此springboot通過攔截器實現(xiàn)攔截黑名單功能已經實現(xiàn)。
到此這篇關于Spring boot攔截器實現(xiàn)IP黑名單的文章就介紹到這了,更多相關Springboot攔截器IP黑名單內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- springboot攔截器過濾token,并返回結果及異常處理操作
- SpringBoot+SpringSecurity 不攔截靜態(tài)資源的實現(xiàn)
- SpringBoot @ControllerAdvice 攔截異常并統(tǒng)一處理
- SpringBoot攔截器如何獲取http請求參數(shù)
- spring boot攔截器的使用場景示例詳解
- SpringBoot攔截器原理解析及使用方法
- SpringBoot配置攔截器方式實例代碼
- SpringBoot攔截器Filter的使用方法詳解
- Spring Boot攔截器和過濾器實例解析
- Spring boot如何基于攔截器實現(xiàn)訪問權限限制
相關文章
在Java中使用redisTemplate操作緩存的方法示例
這篇文章主要介紹了在Java中使用redisTemplate操作緩存的方法示例,在Redis中可以存儲String、List、Set、Hash、Zset。感興趣的可以了解一下2019-01-01
Spring Security OAuth2 實現(xiàn)登錄互踢的示例代碼
這篇文章主要介紹了Spring Security OAuth2實現(xiàn)登錄互踢的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04
quartz實現(xiàn)定時功能實例詳解(servlet定時器配置方法)
Quartz是一個完全由java編寫的開源作業(yè)調度框架,下面提供一個小例子供大家參考,還有在servlet配置的方法2013-12-12
SpringBoot應用War包形式部署到外部Tomcat的方法
這篇文章主要介紹了SpringBoot應用War包形式部署到外部Tomcat的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08
java圖形化界面實現(xiàn)簡單混合運算計算器的示例代碼
這篇文章主要介紹了java圖形化界面實現(xiàn)簡單混合運算計算器的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11
Mybatis中的resultType和resultMap查詢操作實例詳解
resultType是直接表示返回類型的,而resultMap則是對外部ResultMap的引用,resultMap解決復雜查詢是的映射問題。這篇文章主要介紹了Mybatis中的resultType和resultMap查詢操作實例詳解,需要的朋友可以參考下2016-09-09

