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.Entry; 019import com.alibaba.csp.sentinel.EntryType; 020import com.alibaba.csp.sentinel.SphU; 021import com.alibaba.csp.sentinel.annotation.SentinelResource; 022import com.alibaba.csp.sentinel.slots.block.BlockException; 023import com.jfinal.aop.Interceptor; 024import com.jfinal.aop.Invocation; 025 026/** 027 * @author michael yang (fuhai999@gmail.com) 028 * @Date: 2020/1/7 029 */ 030public class SentinelInterceptor extends AbstractSentinelInterceptor implements Interceptor { 031 032 @Override 033 public void intercept(Invocation inv) { 034 035 SentinelResource annotation = inv.getMethod().getAnnotation(SentinelResource.class); 036 if (annotation == null) { 037 inv.invoke(); 038 return; 039 } 040 041 String resourceName = getResourceName(annotation.value(), inv.getMethod()); 042 EntryType entryType = annotation.entryType(); 043 int resourceType = annotation.resourceType(); 044 Entry entry = null; 045 try { 046 entry = SphU.entry(resourceName, resourceType, entryType, inv.getArgs()); 047 inv.invoke(); 048 } catch (BlockException ex) { 049 try { 050 inv.setReturnValue(handleBlockException(inv, annotation, ex)); 051 } catch (Throwable throwable) { 052 if (inv.isActionInvocation()) { 053 SentinelUtil.blockRequest(inv.getController().getRequest(), inv.getController().getResponse()); 054 } else { 055 throwable.printStackTrace(); 056 } 057 } 058 return; 059 } catch (Throwable ex) { 060 Class<? extends Throwable>[] exceptionsToIgnore = annotation.exceptionsToIgnore(); 061 // The ignore list will be checked first. 062 if (exceptionsToIgnore.length > 0 && exceptionBelongsTo(ex, exceptionsToIgnore)) { 063 throw ex; 064 } 065 if (exceptionBelongsTo(ex, annotation.exceptionsToTrace())) { 066 traceException(ex); 067 try { 068 inv.setReturnValue(handleFallback(inv, annotation, ex)); 069 } catch (Throwable throwable) { 070 throwable.printStackTrace(); 071 } 072 return; 073 } 074 075 // No fallback function can handle the exception, so throw it out. 076 throw ex; 077 } finally { 078 if (entry != null) { 079 entry.exit(1, inv.getArgs()); 080 } 081 } 082 } 083 084 085}