feat: sentinel can feel exception though application has configured ExceptionHandler (#3409)

This commit is contained in:
lemonJ 2024-08-20 16:29:38 +08:00 committed by GitHub
parent 02c97fef65
commit b78b09d324
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 178 additions and 36 deletions

View File

@ -28,6 +28,12 @@ public class InterceptorConfig implements WebMvcConfigurer {
// Add to the interceptor list.
registry.addInterceptor(new SentinelWebInterceptor(config)).addPathPatterns("/**");
}
@Bean
public SentinelExceptionAware sentinelExceptionAware(){
//Make exception visible to Sentinel if you have configured ExceptionHandler
return new SentinelExceptionAware();
}
}
```

View File

@ -15,9 +15,6 @@
*/
package com.alibaba.csp.sentinel.adapter.spring.webmvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.ResourceTypeConstants;
@ -29,10 +26,15 @@ import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
/**
* Since request may be reprocessed in flow if any forwarding or including or other action
* happened (see {@link javax.servlet.ServletRequest#getDispatcherType()}) we will only
@ -71,15 +73,15 @@ public abstract class AbstractSentinelInterceptor implements HandlerInterceptor
* @param step
* @return reference count after increasing (initial value as zero to be increased)
*/
private Integer increaseReferece(HttpServletRequest request, String rcKey, int step) {
private Integer increaseReference(HttpServletRequest request, String rcKey, int step) {
Object obj = request.getAttribute(rcKey);
if (obj == null) {
// initial
obj = Integer.valueOf(0);
obj = 0;
}
Integer newRc = (Integer)obj + step;
Integer newRc = (Integer) obj + step;
request.setAttribute(rcKey, newRc);
return newRc;
}
@ -94,7 +96,7 @@ public abstract class AbstractSentinelInterceptor implements HandlerInterceptor
return true;
}
if (increaseReferece(request, this.baseWebMvcConfig.getRequestRefName(), 1) != 1) {
if (increaseReference(request, this.baseWebMvcConfig.getRequestRefName(), 1) != 1) {
return true;
}
@ -136,7 +138,7 @@ public abstract class AbstractSentinelInterceptor implements HandlerInterceptor
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
if (increaseReferece(request, this.baseWebMvcConfig.getRequestRefName(), -1) != 0) {
if (increaseReference(request, this.baseWebMvcConfig.getRequestRefName(), -1) != 0) {
return;
}
@ -168,13 +170,22 @@ public abstract class AbstractSentinelInterceptor implements HandlerInterceptor
}
protected void traceExceptionAndExit(Entry entry, Exception ex) {
if (entry != null) {
if (entry == null) {
return;
}
HttpServletRequest request = getHttpServletRequest();
if (request != null
&& ex == null
&& increaseReference(request, this.baseWebMvcConfig.getRequestRefName() + ":" + BaseWebMvcConfig.REQUEST_REF_EXCEPTION_NAME, 1) == 1) {
//Each interceptor can only catch exception once
ex = (Exception) request.getAttribute(BaseWebMvcConfig.REQUEST_REF_EXCEPTION_NAME);
}
if (ex != null) {
Tracer.traceEntry(ex, entry);
}
entry.exit();
}
}
protected void handleBlockException(HttpServletRequest request, HttpServletResponse response, BlockException e)
throws Exception {
@ -197,4 +208,9 @@ public abstract class AbstractSentinelInterceptor implements HandlerInterceptor
return origin;
}
private HttpServletRequest getHttpServletRequest() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return Objects.isNull(servletRequestAttributes) ? null : servletRequestAttributes.getRequest();
}
}

View File

@ -0,0 +1,47 @@
/*
* Copyright 1999-2019 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.adapter.spring.webmvc;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.BaseWebMvcConfig;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Make exception visible to Sentinel.SentinelExceptionAware should be front of ExceptionHandlerExceptionResolver
* whose order is 0 {@link org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#handlerExceptionResolver}
*
* @author lemonJ
*/
@Order(-1)
public class SentinelExceptionAware implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
addExceptionToRequest(request, ex);
return null;
}
private void addExceptionToRequest(HttpServletRequest httpServletRequest, Exception exception) {
if(BlockException.isBlockException(exception)){
return;
}
httpServletRequest.setAttribute(BaseWebMvcConfig.REQUEST_REF_EXCEPTION_NAME, exception);
}
}

View File

@ -26,6 +26,8 @@ import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginPars
*/
public abstract class BaseWebMvcConfig {
public final static String REQUEST_REF_EXCEPTION_NAME = "$$sentinel_spring_web_entry_attr-exception";
protected String requestAttributeName;
protected String requestRefName;
protected BlockExceptionHandler blockExceptionHandler;

View File

@ -23,6 +23,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import com.alibaba.csp.sentinel.node.ClusterNode;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.clusterbuilder.ClusterBuilderSlot;
@ -128,6 +130,32 @@ public class SentinelSpringMvcIntegrationTest {
assertEquals(1, cn.blockRequest(), 1);
}
@Test
public void testExceptionPerception() throws Exception {
String url = "/bizException";
configureExceptionDegradeRulesFor(url, 2.6, null);
int repeat = 3;
for (int i = 0; i < repeat; i++) {
this.mvc.perform(get(url))
.andExpect(status().isOk())
.andExpect(content().string(new ResultWrapper(-1, "Biz error").toJsonString()));
ClusterNode cn = ClusterBuilderSlot.getClusterNode(url);
assertNotNull(cn);
assertEquals(i + 1, cn.passQps(), 0.01);
}
// This will be blocked and response json.
this.mvc.perform(get(url))
.andExpect(status().isOk())
.andExpect(content().string(ResultWrapper.blocked().toJsonString()));
ClusterNode cn = ClusterBuilderSlot.getClusterNode(url);
assertNotNull(cn);
assertEquals(repeat, cn.passQps(), 0.01);
assertEquals(1, cn.blockRequest(), 1);
}
private void configureRulesFor(String resource, int count, String limitApp) {
FlowRule rule = new FlowRule()
.setCount(count)
@ -150,6 +178,20 @@ public class SentinelSpringMvcIntegrationTest {
FlowRuleManager.loadRules(Collections.singletonList(rule));
}
private void configureExceptionDegradeRulesFor(String resource, double count, String limitApp) {
DegradeRule rule = new DegradeRule()
.setCount(count)
.setStatIntervalMs(1000)
.setMinRequestAmount(1)
.setTimeWindow(5)
.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
rule.setResource(resource);
if (StringUtil.isNotBlank(limitApp)) {
rule.setLimitApp(limitApp);
}
DegradeRuleManager.loadRules(Collections.singletonList(rule));
}
@After
public void cleanUp() {
FlowRuleManager.loadRules(null);

View File

@ -15,17 +15,16 @@
*/
package com.alibaba.csp.sentinel.adapter.spring.webmvc.config;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelExceptionAware;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebTotalInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Config sentinel interceptor
@ -35,6 +34,11 @@ import javax.servlet.http.HttpServletResponse;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Bean
public SentinelExceptionAware sentinelExceptionAware() {
return new SentinelExceptionAware();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//Add sentinel interceptor
@ -48,9 +52,7 @@ public class InterceptorConfig implements WebMvcConfigurer {
//Config
SentinelWebMvcConfig config = new SentinelWebMvcConfig();
config.setBlockExceptionHandler(new BlockExceptionHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
config.setBlockExceptionHandler((request, response, e) -> {
String resourceName = e.getRule().getResource();
//Depending on your situation, you can choose to process or throw
if ("/hello".equals(resourceName)) {
@ -61,7 +63,6 @@ public class InterceptorConfig implements WebMvcConfigurer {
//Handle in global exception handling
throw e;
}
}
});
//Custom configuration if necessary

View File

@ -16,6 +16,7 @@
package com.alibaba.csp.sentinel.adapter.spring.webmvc.config;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.ResultWrapper;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.exception.BizException;
import com.alibaba.csp.sentinel.slots.block.AbstractRule;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.slf4j.Logger;
@ -51,4 +52,11 @@ public class SentinelSpringMvcBlockHandlerConfig {
logger.error("System error", e.getMessage());
return new ResultWrapper(-1, "System error");
}
@ExceptionHandler(BizException.class)
@ResponseBody
public ResultWrapper bizExceptionHandler(BizException e) {
logger.error("Biz error", e.getMessage());
return new ResultWrapper(-1, "Biz error");
}
}

View File

@ -16,6 +16,7 @@
package com.alibaba.csp.sentinel.adapter.spring.webmvc.controller;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.exception.BizException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@ -47,6 +48,11 @@ public class TestController {
return "runtimeException";
}
@GetMapping("/bizException")
public String bizException() {
throw new BizException();
}
@GetMapping("/exclude/{id}")
public String apiExclude(@PathVariable("id") Long id) {
return "Exclude " + id;

View File

@ -0,0 +1,7 @@
package com.alibaba.csp.sentinel.adapter.spring.webmvc.exception;
/**
* @author lemonj
*/
public class BizException extends RuntimeException{
}

View File

@ -15,12 +15,13 @@
*/
package com.alibaba.csp.sentinel.demo.spring.webmvc.config;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelExceptionAware;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebTotalInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.DefaultBlockExceptionHandler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcConfig;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcTotalConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ -39,6 +40,12 @@ public class InterceptorConfig implements WebMvcConfigurer {
addSpringMvcInterceptor(registry);
}
@Bean
public SentinelExceptionAware sentinelExceptionAware() {
//Make exception visible to Sentinel if you have configured ExceptionHandler
return new SentinelExceptionAware();
}
private void addSpringMvcInterceptor(InterceptorRegistry registry) {
SentinelWebMvcConfig config = new SentinelWebMvcConfig();