Sentinel current limiting circuit breaker of microservices (1)-Spring MVC custom URL current limiting exception

By default, the URL will return directly after the current limit is triggered.

Blocked by Sentinel(flow limiting)

In actual applications, most of the data is in JSON format, so if you want to modify the return result form after triggering the current limit, you can handle it by customizing the current limit exception, implement UrlBlockHandler and rewrite the blocked method:

package xxx;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CustomUrlBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       BlockException ex) throws Exception {
        response.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        String message = "{\"code\":999,\"msg\":\"访问人数过多\"}";
        response.getWriter().write(message);
    }
}

Another scenario is that when the current limit is triggered, for the ToB application, we hope to jump directly to a degraded page, which can be achieved through the following configuration.

spring.sentinel.servlet.block-page.url={url}

Guess you like

Origin blog.csdn.net/weixin_39195030/article/details/112726073