Sentinel如何使用BlockExceptionHandler实现限流/降级错误页面显示

1、修改配置项,打开对Spring MVC端点的保护

spring.cloud.sentinel.filter.enabled=true

2、编写 BlockExceptionHandler的实现类

复制代码
MyUrlBlockHandler.java
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
{
    @Override
    public 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操作工具,叫jackson
        new ObjectMapper()
            .writeValue(
                response.getWriter(),
                msg
            );
    }

}

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
class ErrorMsg {
    private Integer status;
    private String msg;
}
相关推荐
魔道不误砍柴功2 小时前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python
NiNg_1_2342 小时前
SpringBoot整合SpringSecurity实现密码加密解密、登录认证退出功能
java·spring boot·后端
闲晨2 小时前
C++ 继承:代码传承的魔法棒,开启奇幻编程之旅
java·c语言·开发语言·c++·经验分享
测开小菜鸟3 小时前
使用python向钉钉群聊发送消息
java·python·钉钉
P.H. Infinity4 小时前
【RabbitMQ】04-发送者可靠性
java·rabbitmq·java-rabbitmq
生命几十年3万天4 小时前
java的threadlocal为何内存泄漏
java
caridle4 小时前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express
^velpro^5 小时前
数据库连接池的创建
java·开发语言·数据库
苹果醋35 小时前
Java8->Java19的初步探索
java·运维·spring boot·mysql·nginx
秋の花5 小时前
【JAVA基础】Java集合基础
java·开发语言·windows