webmvc-adapter: improve to avoid ErrorEntryFreeException (#1533)

If entry already exists in request just skip creation.
This commit is contained in:
cdfive 2020-08-19 23:55:11 +08:00 committed by GitHub
parent bcbc19c772
commit a1ce97677c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 12 additions and 4 deletions

View File

@ -61,9 +61,7 @@ public abstract class AbstractSentinelInterceptor implements HandlerInterceptor
String origin = parseOrigin(request); String origin = parseOrigin(request);
String contextName = getContextName(request); String contextName = getContextName(request);
ContextUtil.enter(contextName, origin); ContextUtil.enter(contextName, origin);
Entry entry = SphU.entry(resourceName, ResourceTypeConstants.COMMON_WEB, EntryType.IN); setEntryInRequest(request, baseWebMvcConfig.getRequestAttributeName(), resourceName);
setEntryInRequest(request, baseWebMvcConfig.getRequestAttributeName(), entry);
} }
return true; return true;
} catch (BlockException e) { } catch (BlockException e) {
@ -110,12 +108,22 @@ public abstract class AbstractSentinelInterceptor implements HandlerInterceptor
ModelAndView modelAndView) throws Exception { ModelAndView modelAndView) throws Exception {
} }
protected void setEntryInRequest(HttpServletRequest request, String name, Entry entry) { /**
* Note:
* If the attribute key already exists in request, don't create new {@link Entry},
* to guarantee the order of {@link Entry} in pair and avoid {@link com.alibaba.csp.sentinel.ErrorEntryFreeException}.
*
* Refer to:
* https://github.com/alibaba/Sentinel/issues/1531
* https://github.com/alibaba/Sentinel/issues/1482
*/
protected void setEntryInRequest(HttpServletRequest request, String name, String resourceName) throws BlockException {
Object attrVal = request.getAttribute(name); Object attrVal = request.getAttribute(name);
if (attrVal != null) { if (attrVal != null) {
RecordLog.warn("[{}] The attribute key '{}' already exists in request, please set `requestAttributeName`", RecordLog.warn("[{}] The attribute key '{}' already exists in request, please set `requestAttributeName`",
getClass().getSimpleName(), name); getClass().getSimpleName(), name);
} else { } else {
Entry entry = SphU.entry(resourceName, ResourceTypeConstants.COMMON_WEB, EntryType.IN);
request.setAttribute(name, entry); request.setAttribute(name, entry);
} }
} }