1、修改配置项,打开对Spring MVC端点的保护
spring.cloud.sentinel.filter.enabled=true
2、编写 BlockExceptionHandler的实现类
MyUrlBlockHandler.java
package com.codex.terry.sentinel.urlblockhandler;/*** 文件名称: MyUrlBlockHandler.java* 编写人: yh.zeng* 编写时间: 2024/6/28 13:50* 文件描述: todo*/import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@Component
@Slf4j
public class MyUrlBlockHandler implements BlockExceptionHandler
{@Overridepublic void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {ErrorMsg msg = null;if (e instanceof FlowException) {log.error("限流了");msg = ErrorMsg.builder().status(100).msg("限流了").build();} else if (e instanceof DegradeException) {log.error("降级了 ");msg = ErrorMsg.builder().status(101).msg("降级了").build();} else if (e instanceof ParamFlowException) {log.error("热点参数限流");msg = ErrorMsg.builder().status(102).msg("热点参数限流").build();} else if (e instanceof SystemBlockException) {log.error("系统规则(负载/...不满足要求)");msg = ErrorMsg.builder().status(103).msg("系统规则(负载/...不满足要求)").build();} else if (e instanceof AuthorityException) {log.error("授权规则不通过");msg = ErrorMsg.builder().status(104).msg("授权规则不通过").build();}// http状态码response.setStatus(500);response.setCharacterEncoding("utf-8");response.setHeader("Content-Type", "application/json;charset=utf-8");response.setContentType("application/json;charset=utf-8");// spring mvc自带的json操作工具,叫jacksonnew ObjectMapper().writeValue(response.getWriter(),msg);}}@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
class ErrorMsg {private Integer status;private String msg;
}