Sentinel 授權規則詳解與自定義異常處理
在微服務系統中,權限控制和訪問保護是至關重要的一環。本文將詳細介紹如何通過 Sentinel 的 授權規則(AuthorityRule) 控制資源訪問權限,并結合實際案例說明如何設置白名單與黑名單,以及如何實現 自定義異常返回,提升系統的穩定性與用戶體驗。
一、Sentinel 授權規則
授權規則用于對資源進行訪問權限控制,其核心思想是:
給指定資源配置“流控應用”,然后通過 白名單 或 黑名單 控制不同來源是否能訪問。
- 白名單(Whitelist):只有在白名單中的應用可以訪問。
- 黑名單(Blacklist):黑名單中的應用不能訪問,其他應用可以正常訪問。
如何設置請求來源(流控應用)?
Sentinel 默認不識別請求的來源,我們需要自定義 RequestOriginParser
接口來識別請求參數,從而指定來源。
自定義來源解析器
package com.southwind.configuration;import com.alibaba.csp.sentinel.adapter.servlet.callback.RequestOriginParser;
import org.springframework.util.StringUtils;import javax.servlet.http.HttpServletRequest;public class RequestOriginParserDefinition implements RequestOriginParser {@Overridepublic String parseOrigin(HttpServletRequest request) {String name = request.getParameter("name");if (StringUtils.isEmpty(name)) {throw new RuntimeException("name is null");}return name;}
}
注入配置類使其生效
package com.southwind.configuration;import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import org.springframework.context.annotation.Configuration;import javax.annotation.PostConstruct;@Configuration
public class SentinelConfiguration {@PostConstructpublic void init() {WebCallbackManager.setRequestOriginParser(new RequestOriginParserDefinition());}
}
二、授權規則效果展示
示例:假設我們對接口 /test
添加授權規則,限制訪問來源。
白名單效果
配置白名單為 aaa
,那么只有 name=aaa
的請求能通過:
http://localhost:8080/test?name=aaa
其他任何非 aaa
的請求都將被攔截。
(示意圖:白名單正常訪問請求截圖)
黑名單效果
配置黑名單為 tom
,表示禁止 name=tom
的請求:
http://localhost:8080/test?name=tom
其它名稱的請求如 name=jerry
可以正常訪問。
(示意圖:黑名單攔截請求截圖)
三、自定義規則異常處理
當請求被 Sentinel 攔截(如限流、降級、授權失敗等),可以通過 UrlBlockHandler
接口進行統一異常處理,返回更加友好的信息。
創建自定義異常處理器
package com.southwind.handler;import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class ExceptionHandler implements UrlBlockHandler {@Overridepublic void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {response.setContentType("text/html;charset=utf-8");String msg = "訪問受限:";if (e instanceof FlowException) {msg += "觸發限流";} else if (e instanceof DegradeException) {msg += "觸發降級";}response.getWriter().write(msg);}
}
在配置類中注冊異常處理器
@Configuration
public class SentinelConfiguration {@PostConstructpublic void init() {WebCallbackManager.setUrlBlockHandler(new ExceptionHandler());}
}
四、總結
功能模塊 | 說明 |
---|---|
授權規則 | 通過白名單/黑名單控制來源訪問權限 |
請求來源設置 | 實現 RequestOriginParser 指定來源參數 |
自定義異常 | 實現 UrlBlockHandler 提供更友好提示 |
配置生效 | 在 @Configuration 中注入配置 |
通過上述配置,我們不僅實現了資源訪問控制,還優化了 Sentinel 異常返回信息,讓系統既安全又具備良好的用戶體驗。
參考資料:
- Sentinel 官網:https://github.com/alibaba/Sentinel
- Spring Boot + Sentinel 實踐示例
如覺得有幫助,歡迎點贊、收藏、評論支持!
更多后端開發實踐內容持續更新中。