001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.jboot.support.sentinel; 017 018import com.alibaba.csp.sentinel.*; 019import com.alibaba.csp.sentinel.context.ContextUtil; 020import com.alibaba.csp.sentinel.slots.block.BlockException; 021import com.jfinal.handler.Handler; 022import io.jboot.utils.StrUtil; 023 024import javax.servlet.http.HttpServletRequest; 025import javax.servlet.http.HttpServletResponse; 026 027 028public class SentinelHandler extends Handler { 029 030 private static final String EMPTY_ORIGIN = ""; 031 032 private final String[] targetPrefix; 033 034 public SentinelHandler() { 035 targetPrefix = parseTargetPrefix(); 036 } 037 038 private String[] parseTargetPrefix() { 039 String reqeustTargetPrefix = SentinelConfig.get().getReqeustTargetPrefix(); 040 if (StrUtil.isBlank(reqeustTargetPrefix)) { 041 return new String[0]; 042 } else { 043 return StrUtil.splitToSet(reqeustTargetPrefix, ",").toArray(new String[0]); 044 } 045 } 046 047 @Override 048 public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) { 049 050 // 不对静态资源进行流量管理 051 if (target.contains(".")) { 052 next.handle(target, request, response, isHandled); 053 return; 054 } 055 056 //配置了前缀的情况 057 if (targetPrefix.length > 0) { 058 boolean matchTarget = false; 059 for (String prefx : targetPrefix) { 060 if (target.startsWith(prefx)) { 061 matchTarget = true; 062 break; 063 } 064 } 065 066 if (!matchTarget) { 067 next.handle(target, request, response, isHandled); 068 return; 069 } 070 } 071 072 073 Entry urlEntry = null; 074 try { 075 String targetResource = SentinelUtil.buildResource(request); 076 077 if (StrUtil.isNotBlank(targetResource)) { 078 ContextUtil.enter(targetResource, getOrigin(request)); 079 urlEntry = SphU.entry(targetResource, ResourceTypeConstants.COMMON_WEB, EntryType.IN); 080 } 081 082 next.handle(target, request, response, isHandled); 083 } catch (BlockException e) { 084 SentinelUtil.blockRequest(request, response); 085 isHandled[0] = true; 086 } catch (Exception e2) { 087 Tracer.traceEntry(e2, urlEntry); 088 throw e2; 089 } finally { 090 if (urlEntry != null) { 091 urlEntry.exit(); 092 } 093 ContextUtil.exit(); 094 } 095 096 } 097 098 protected String getOrigin(HttpServletRequest request) { 099 return EMPTY_ORIGIN; 100 } 101 102 103}