diff --git a/sentinel-core/src/main/java/com/alibaba/csp/sentinel/annotation/SentinelResource.java b/sentinel-core/src/main/java/com/alibaba/csp/sentinel/annotation/SentinelResource.java index d23fa7d8..98a73c87 100644 --- a/sentinel-core/src/main/java/com/alibaba/csp/sentinel/annotation/SentinelResource.java +++ b/sentinel-core/src/main/java/com/alibaba/csp/sentinel/annotation/SentinelResource.java @@ -24,7 +24,10 @@ import java.lang.annotation.Target; import com.alibaba.csp.sentinel.EntryType; /** + * The annotation indicates a definition of Sentinel resource. + * * @author Eric Zhao + * @since 0.1.1 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @@ -46,6 +49,16 @@ public @interface SentinelResource { */ String blockHandler() default ""; + /** + * The {@code blockHandler} is located in the same class with the original method by default. + * However, if some methods share the same signature and intend to set the same block handler, + * then users can set the class where the block handler exists. Note that the block handler method + * must be static. + * + * @return the class where the block handler exists, should not provide more than one classes + */ + Class[] blockHandlerClass() default {}; + /** * @return name of the fallback function, empty by default */ diff --git a/sentinel-core/src/main/java/com/alibaba/csp/sentinel/log/RecordLog.java b/sentinel-core/src/main/java/com/alibaba/csp/sentinel/log/RecordLog.java index a4f8b7b1..3c4db12f 100755 --- a/sentinel-core/src/main/java/com/alibaba/csp/sentinel/log/RecordLog.java +++ b/sentinel-core/src/main/java/com/alibaba/csp/sentinel/log/RecordLog.java @@ -50,4 +50,14 @@ public class RecordLog extends LogBase { LoggerUtils.disableOtherHandlers(heliumRecordLog, logHandler); heliumRecordLog.log(Level.INFO, detail, e); } + + public static void warn(String detail) { + LoggerUtils.disableOtherHandlers(heliumRecordLog, logHandler); + heliumRecordLog.log(Level.WARNING, detail); + } + + public static void warn(String detail, Throwable e) { + LoggerUtils.disableOtherHandlers(heliumRecordLog, logHandler); + heliumRecordLog.log(Level.WARNING, detail, e); + } } diff --git a/sentinel-demo/sentinel-demo-annotation-spring-aop/src/main/java/com/alibaba/csp/sentinel/demo/annotation/aop/service/ExceptionUtil.java b/sentinel-demo/sentinel-demo-annotation-spring-aop/src/main/java/com/alibaba/csp/sentinel/demo/annotation/aop/service/ExceptionUtil.java new file mode 100644 index 00000000..e589f85b --- /dev/null +++ b/sentinel-demo/sentinel-demo-annotation-spring-aop/src/main/java/com/alibaba/csp/sentinel/demo/annotation/aop/service/ExceptionUtil.java @@ -0,0 +1,28 @@ +/* + * Copyright 1999-2018 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 + * + * http://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.demo.annotation.aop.service; + +import com.alibaba.csp.sentinel.slots.block.BlockException; + +/** + * @author Eric Zhao + */ +public final class ExceptionUtil { + + public static void handleException(BlockException ex) { + System.out.println("Oops: " + ex.getClass().getCanonicalName()); + } +} diff --git a/sentinel-demo/sentinel-demo-annotation-spring-aop/src/main/java/com/alibaba/csp/sentinel/demo/annotation/aop/service/TestServiceImpl.java b/sentinel-demo/sentinel-demo-annotation-spring-aop/src/main/java/com/alibaba/csp/sentinel/demo/annotation/aop/service/TestServiceImpl.java index d7f061a6..ab1437e6 100644 --- a/sentinel-demo/sentinel-demo-annotation-spring-aop/src/main/java/com/alibaba/csp/sentinel/demo/annotation/aop/service/TestServiceImpl.java +++ b/sentinel-demo/sentinel-demo-annotation-spring-aop/src/main/java/com/alibaba/csp/sentinel/demo/annotation/aop/service/TestServiceImpl.java @@ -27,7 +27,7 @@ import org.springframework.stereotype.Service; public class TestServiceImpl implements TestService { @Override - @SentinelResource("test") + @SentinelResource(value = "test", blockHandler = "handleException", blockHandlerClass = {ExceptionUtil.class}) public void test() { System.out.println("Test"); } diff --git a/sentinel-extension/sentinel-annotation-aspectj/README.md b/sentinel-extension/sentinel-annotation-aspectj/README.md index 36227658..6960ed52 100644 --- a/sentinel-extension/sentinel-annotation-aspectj/README.md +++ b/sentinel-extension/sentinel-annotation-aspectj/README.md @@ -9,8 +9,14 @@ The `@SentinelResource` annotation indicates a resource definition, including: - `value`: Resource name, required (cannot be empty) - `entryType`: Resource entry type (inbound or outbound), `EntryType.OUT` by default -- `fallback`: Fallback method when degraded (optional). The fallback method should be located in the same class with original method. The signature of the fallback method should match the original method (parameter types and return type) -- `blockHandler`: Handler method that handles `BlockException` when blocked. The block handler method should be located in the same class with original method, and the signature should match original method, with the last additional parameter type `BlockException`. +- `fallback`: Fallback method when degraded (optional). +The fallback method should be located in the same class with original method. +The signature of the fallback method should match the original method (parameter types and return type). +- `blockHandler`: Handler method that handles `BlockException` when blocked. +The signature should match original method, with the last additional parameter type `BlockException`. +The block handler method should be located in the same class with original method by default. +If you want to use method in other classes, you can set the `blockHandlerClass` with corresponding `Class` +(Note the method in other classes must be *static*). For example: diff --git a/sentinel-extension/sentinel-annotation-aspectj/pom.xml b/sentinel-extension/sentinel-annotation-aspectj/pom.xml index fdd2ff91..5fbe7da7 100644 --- a/sentinel-extension/sentinel-annotation-aspectj/pom.xml +++ b/sentinel-extension/sentinel-annotation-aspectj/pom.xml @@ -32,6 +32,12 @@ aspectjweaver ${aspectj.version} + + + org.slf4j + slf4j-api + 1.7.25 + \ No newline at end of file diff --git a/sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/ResourceMetadataRegistry.java b/sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/ResourceMetadataRegistry.java index 1fb0ce7f..fcb276f4 100644 --- a/sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/ResourceMetadataRegistry.java +++ b/sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/ResourceMetadataRegistry.java @@ -22,36 +22,38 @@ import java.util.concurrent.ConcurrentHashMap; import com.alibaba.csp.sentinel.util.StringUtil; /** + * Registry for resource configuration metadata (e.g. fallback method) + * * @author Eric Zhao */ -public final class ResourceMetadataRegistry { +final class ResourceMetadataRegistry { private static final Map FALLBACK_MAP = new ConcurrentHashMap(); private static final Map BLOCK_HANDLER_MAP = new ConcurrentHashMap(); - public static MethodWrapper lookupFallback(Class clazz, String name) { + static MethodWrapper lookupFallback(Class clazz, String name) { return FALLBACK_MAP.get(getKey(clazz, name)); } - public static MethodWrapper lookupBlockHandler(Class clazz, String name) { + static MethodWrapper lookupBlockHandler(Class clazz, String name) { return BLOCK_HANDLER_MAP.get(getKey(clazz, name)); } - public static void updateFallbackFor(Class clazz, String name, Method method) { + static void updateFallbackFor(Class clazz, String name, Method method) { if (clazz == null || StringUtil.isBlank(name)) { throw new IllegalArgumentException("Bad argument"); } FALLBACK_MAP.put(getKey(clazz, name), MethodWrapper.wrap(method)); } - public static void updateBlockHandlerFor(Class clazz, String name, Method method) { + static void updateBlockHandlerFor(Class clazz, String name, Method method) { if (clazz == null || StringUtil.isBlank(name)) { throw new IllegalArgumentException("Bad argument"); } BLOCK_HANDLER_MAP.put(getKey(clazz, name), MethodWrapper.wrap(method)); } - public static String getKey(Class clazz, String name) { + private static String getKey(Class clazz, String name) { return String.format("%s:%s", clazz.getCanonicalName(), name); } } diff --git a/sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/SentinelResourceAspect.java b/sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/SentinelResourceAspect.java index f4cea7b8..21f3bfc0 100644 --- a/sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/SentinelResourceAspect.java +++ b/sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/SentinelResourceAspect.java @@ -16,6 +16,7 @@ package com.alibaba.csp.sentinel.annotation.aspectj; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.util.Arrays; import com.alibaba.csp.sentinel.Entry; @@ -33,6 +34,8 @@ import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Aspect for methods with {@link SentinelResource} annotation. @@ -42,6 +45,8 @@ import org.aspectj.lang.reflect.MethodSignature; @Aspect public class SentinelResourceAspect { + private final Logger logger = LoggerFactory.getLogger(SentinelResourceAspect.class); + @Pointcut("@annotation(com.alibaba.csp.sentinel.annotation.SentinelResource)") public void sentinelResourceAnnotationPointcut() { } @@ -84,10 +89,14 @@ public class SentinelResourceAspect { } } // Execute block handler if configured. - Method blockHandler = extractBlockHandlerMethod(pjp, annotation.blockHandler()); + Method blockHandler = extractBlockHandlerMethod(pjp, annotation.blockHandler(), annotation.blockHandlerClass()); if (blockHandler != null) { + // Construct args. Object[] args = Arrays.copyOf(originArgs, originArgs.length + 1); args[args.length - 1] = ex; + if (isStatic(blockHandler)) { + return blockHandler.invoke(null, args); + } return blockHandler.invoke(pjp.getTarget(), args); } // If no block handler is present, then directly throw the exception. @@ -120,38 +129,26 @@ public class SentinelResourceAspect { private Method resolveFallbackInternal(ProceedingJoinPoint pjp, /*@NonNull*/ String name) { Method originMethod = getMethod(pjp); Class[] parameterTypes = originMethod.getParameterTypes(); - return findMethod(pjp.getTarget().getClass(), name, originMethod.getReturnType(), parameterTypes); + return findMethod(false, pjp.getTarget().getClass(), name, originMethod.getReturnType(), parameterTypes); } - private Method findMethod(Class clazz, String name, Class returnType, Class... parameterTypes) { - Method[] methods = clazz.getDeclaredMethods(); - for (Method method : methods) { - if (name.equals(method.getName()) && returnType.isAssignableFrom(method.getReturnType()) - && Arrays.equals(parameterTypes, method.getParameterTypes())) { - return method; - } - } - // Current class nou found, find in the super classes recursively. - Class superClass = clazz.getSuperclass(); - if (superClass != null && !Object.class.equals(superClass)) { - return findMethod(superClass, name, returnType, parameterTypes); - } else { - RecordLog.info( - String.format("[SentinelResourceAspect] Cannot find method [%s] in class [%s] with parameters %s", - name, clazz.getCanonicalName(), Arrays.toString(parameterTypes))); + private Method extractBlockHandlerMethod(ProceedingJoinPoint pjp, String name, Class[] locationClass) { + if (StringUtil.isBlank(name)) { return null; } - } - private Method extractBlockHandlerMethod(ProceedingJoinPoint pjp, String name) { - if (StringUtil.isBlank(name)) { - return null; + boolean mustStatic = locationClass != null && locationClass.length >= 1; + Class clazz; + if (mustStatic) { + clazz = locationClass[0]; + } else { + // By default current class. + clazz = pjp.getTarget().getClass(); } - Class clazz = pjp.getTarget().getClass(); MethodWrapper m = ResourceMetadataRegistry.lookupBlockHandler(clazz, name); if (m == null) { // First time, resolve the block handler. - Method method = resolveBlockHandlerInternal(pjp, name); + Method method = resolveBlockHandlerInternal(pjp, name, clazz, mustStatic); // Cache the method instance. ResourceMetadataRegistry.updateBlockHandlerFor(clazz, name, method); return method; @@ -162,12 +159,45 @@ public class SentinelResourceAspect { return m.getMethod(); } - private Method resolveBlockHandlerInternal(ProceedingJoinPoint pjp, /*@NonNull*/ String name) { + private Method resolveBlockHandlerInternal(ProceedingJoinPoint pjp, /*@NonNull*/ String name, Class clazz, + boolean mustStatic) { Method originMethod = getMethod(pjp); Class[] originList = originMethod.getParameterTypes(); Class[] parameterTypes = Arrays.copyOf(originList, originList.length + 1); parameterTypes[parameterTypes.length - 1] = BlockException.class; - return findMethod(pjp.getTarget().getClass(), name, originMethod.getReturnType(), parameterTypes); + return findMethod(mustStatic, clazz, name, originMethod.getReturnType(), parameterTypes); + } + + private boolean checkStatic(boolean mustStatic, Method method) { + return !mustStatic || isStatic(method); + } + + private Method findMethod(boolean mustStatic, Class clazz, String name, Class returnType, + Class... parameterTypes) { + Method[] methods = clazz.getDeclaredMethods(); + for (Method method : methods) { + if (name.equals(method.getName()) && checkStatic(mustStatic, method) + && returnType.isAssignableFrom(method.getReturnType()) + && Arrays.equals(parameterTypes, method.getParameterTypes())) { + + logger.info("Resolved method [{}] in class [{}]", name, clazz.getCanonicalName()); + return method; + } + } + // Current class not found, find in the super classes recursively. + Class superClass = clazz.getSuperclass(); + if (superClass != null && !Object.class.equals(superClass)) { + return findMethod(mustStatic, superClass, name, returnType, parameterTypes); + } else { + String methodType = mustStatic ? " static" : ""; + logger.error("Cannot find{} method [{}] in class [{}] with parameters {}", + methodType, name, clazz.getCanonicalName(), Arrays.toString(parameterTypes)); + return null; + } + } + + private boolean isStatic(Method method) { + return Modifier.isStatic(method.getModifiers()); } private Method getMethod(ProceedingJoinPoint joinPoint) {