我們都知道Sentinel默認的回滾提示是Blocked by Sentinel
而且我也給大家演示了如何寫自定義的回滾方法。

image.png
但是這樣寫還有一些問題:
①依照現(xiàn)有條件,我們自定義的處理方法又和業(yè)務代碼耦合在一起,不直觀。
②每個業(yè)務方法都要有一個自定義的回滾方法,很容易使代碼膨脹加劇。
③沒有體現(xiàn)全局的統(tǒng)一處理方法
針對這幾個問題,Sentinel也是有解決方案的
1.新建統(tǒng)一的BlockHandler處理類
public class CustomerBlockHandler {
public static CommonResult handlerException(BlockException exception)
{
return new CommonResult(4444,"按客戶自定義,global handlerException----1");
}
public static CommonResult handlerException2(BlockException exception)
{
return new CommonResult(4444,"按客戶自定義,global handlerException----2");
}
}
CommonResult 是我自己寫的自定義的統(tǒng)一返回對象,這個handler里面有兩個方法,分別打印的---1和---2。
2.新建一個測試的controller方法
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class,
blockHandler = "handlerException2")
public CommonResult customerBlockHandler()
{
return new CommonResult(200,"按客戶自定義",new Payment(2020L,"serial003"));
}
SentinelResource屬性說明:
value是資源名,可以通過sentinel控制臺直接配置資源名來進行限流
blockHandlerClass是配置我們的全局統(tǒng)一回滾方法的處理類。
blockHandler配置的是具體的方法。

image.png
3.在sentinel控制臺新增一個流控規(guī)則

image.png
可以看到我們配置是@SentinelResource里面的資源名,而不是GetMapping。
4.測試
正常發(fā)送一下是沒有問題的

image.png
接下來觀察流控的效果

image.png
可以看到返回的是統(tǒng)一回滾方法里面的第二個方法,說明我們的配置是生效的。