Sentinel限流之后,默认的响应消息为Blocked by Sentinel (flow limiting),对于系统整体功能提示来说并不统一,参考我们前面设置的统一响应及异常处理方式,返回相同的格式的消息。
1、在自定义Sentinel返回消息之前,需要调整一下代码结构,因为这里要用到统一返回异常的格式,考虑到后期可能的使用问题,这里需要把gitegg-platform-boot工程里定义的统一响应及异常移到新建的gitegg-platform-base通用定义工程里面,同时在gitegg-platform-cloud中引入gitegg-platform-base和spring-boot-starter-web
<!-- 为了使用HttpServletRequest和HttpServletResponse --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.gitegg.platform</groupId> <artifactId>gitegg-platform-base</artifactId> </dependency>
2、在GitEgg-Platform子工程gitegg-platform-cloud中自定义Sentinel错误处理类GitEggBlockExceptionHandler.java:
package com.gitegg.platform.cloud.sentinel.handler; import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.fasterxml.jackson.databind.ObjectMapper; import com.gitegg.platform.base.enums.ResultCodeEnum; import com.gitegg.platform.base.result.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 自定义异常处理器 */ @Slf4j @Component public class GitEggBlockExceptionHandler implements BlockExceptionHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception { response.setStatus(429); response.setContentType("application/json;charset=utf-8"); Result result = Result.error(ResultCodeEnum.SYSTEM_BUSY, ResultCodeEnum.SYSTEM_BUSY.getMsg()); new ObjectMapper().writeValue(response.getWriter(), result); } }
3、配置Sentinel控制台,配置容易出现限流的规则,打开Jmeter进行测试,我们可以看到返回消息已经是我们自定义的格式了:
image.png