kk-anti-reptile 是適用於基於 spring-boot 開發的分佈式系統的反爬蟲組件。原文http://33s.co/6s37
系統要求
基於 spring-boot 開發(spring-boot1.x, spring-boot2.x均可)
需要使用 redis
工作流程
kk-anti-reptile 使用基於 Servlet 規範的的 Filter 對請求進行過濾,在其內部通過 spring-boot 的擴展點機制,實例化一個 Filter,並注入到 Spring 容器 FilterRegistrationBean 中,通過 Spring 注入到 Servlet 容器中,從而實現對請求的過濾。
在 kk-anti-reptile 的過濾 Filter 內部,又通過責任鏈模式,將各種不同的過濾規則織入,並提供抽象接口,可由調用方進行規則擴展。
Filter 調用則鏈進行請求過濾,如過濾不通過,則攔截請求,返回狀態碼 509,並輸出驗證碼輸入頁面,輸出驗證碼正確後,調用過濾規則鏈對規則進行重置。
目前規則鏈中有如下兩個規則
ip-rule
ip-rule 通過時間窗口統計當前時間窗口內請求數,小於規定的最大請求數則可通過,否則不通過。時間窗口、最大請求數、ip 白名單等均可配置。
ua-rule
ua-rule 通過判斷請求攜帶的 User-Agent,得到操作系統、設備信息、瀏覽器信息等,可配置各種維度對請求進行過濾。
命中規則後
命中爬蟲和防盜刷規則後,會阻斷請求,並生成接除阻斷的驗證碼,驗證碼有多種組合方式,如果客戶端可以正確輸入驗證碼,則可以繼續訪問
驗證碼有中文、英文字母+數字、簡單算術三種形式,每種形式又有靜態圖片和 GIF 動圖兩種圖片格式,即目前共有如下六種,所有類型的驗證碼會隨機出現,目前技術手段識別難度極高,可有效阻止防止爬蟲大規模爬取數據
接入使用
後端接入非常簡單,只需要引用 kk-anti-reptile 的 maven 依賴,並配置啓用 kk-anti-reptile 即可加入 maven 依賴
- <dependency>
- <groupId>cn.keking.project</groupId>
- <artifactId>kk-anti-reptile</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </dependency>
配置啓用 kk-anti-reptile
- anti.reptile.manager.enabled=true
前端需要在統一發送請求的 ajax 處加入攔截,攔截到請求返回狀態碼 509 後彈出一個新頁面,並把響應內容轉出到頁面中,然後向頁面中傳入後端接口 baseUrl 參數即可,以使用 axios 請求爲例:
- import axios from 'axios';
- import {baseUrl} from './config';
- axios.interceptors.response.use(
- data => {
- return data;
- },
- error => {
- if (error.response.status === 509) {
- let html = error.response.data;
- let verifyWindow = window.open("","_blank","height=400,width=560");
- verifyWindow.document.write(html);
- verifyWindow.document.getElementById("baseUrl").value = baseUrl;
- }
- }
- );
- export default axios;
注意
apollo-client 需啓用 bootstrap
使用 apollo 配置中心的用戶,由於組件內部用到 @ConditionalOnProperty,要在 application.properties/bootstrap.properties 中加入如下樣例配置,(apollo-client 需要 0.10.0 及以上版本)詳見 apollo bootstrap 說明
- apollo.bootstrap.enabled = true
- 需要有 Redisson
連接如果項目中有用到 Redisson,kk-anti-reptile 會自動獲取 RedissonClient 實例對象; 如果沒用到,需要在配置文件加入如下 Redisson 連接相關配置:
- spring.redisson.address=redis://192.168.1.204:6379
- spring.redisson.password=xxx
配置一覽表
在 spring-boot 中,所有配置在配置文件都會有自動提示和說明,如下圖:
所有配置都以 anti.reptile.manager 爲前綴,如下爲所有配置項及說明: