Browse Source

Add support for shared block handler

- Update javadoc and document

Signed-off-by: Eric Zhao <sczyh16@gmail.com>
master
Eric Zhao 6 years ago
parent
commit
b1cf30fc24
8 changed files with 130 additions and 35 deletions
  1. +13
    -0
      sentinel-core/src/main/java/com/alibaba/csp/sentinel/annotation/SentinelResource.java
  2. +10
    -0
      sentinel-core/src/main/java/com/alibaba/csp/sentinel/log/RecordLog.java
  3. +28
    -0
      sentinel-demo/sentinel-demo-annotation-spring-aop/src/main/java/com/alibaba/csp/sentinel/demo/annotation/aop/service/ExceptionUtil.java
  4. +1
    -1
      sentinel-demo/sentinel-demo-annotation-spring-aop/src/main/java/com/alibaba/csp/sentinel/demo/annotation/aop/service/TestServiceImpl.java
  5. +8
    -2
      sentinel-extension/sentinel-annotation-aspectj/README.md
  6. +6
    -0
      sentinel-extension/sentinel-annotation-aspectj/pom.xml
  7. +8
    -6
      sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/ResourceMetadataRegistry.java
  8. +56
    -26
      sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/SentinelResourceAspect.java

+ 13
- 0
sentinel-core/src/main/java/com/alibaba/csp/sentinel/annotation/SentinelResource.java View File

@@ -24,7 +24,10 @@ import java.lang.annotation.Target;
import com.alibaba.csp.sentinel.EntryType; import com.alibaba.csp.sentinel.EntryType;


/** /**
* The annotation indicates a definition of Sentinel resource.
*
* @author Eric Zhao * @author Eric Zhao
* @since 0.1.1
*/ */
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@@ -46,6 +49,16 @@ public @interface SentinelResource {
*/ */
String blockHandler() default ""; 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 * @return name of the fallback function, empty by default
*/ */


+ 10
- 0
sentinel-core/src/main/java/com/alibaba/csp/sentinel/log/RecordLog.java View File

@@ -50,4 +50,14 @@ public class RecordLog extends LogBase {
LoggerUtils.disableOtherHandlers(heliumRecordLog, logHandler); LoggerUtils.disableOtherHandlers(heliumRecordLog, logHandler);
heliumRecordLog.log(Level.INFO, detail, e); 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);
}
} }

+ 28
- 0
sentinel-demo/sentinel-demo-annotation-spring-aop/src/main/java/com/alibaba/csp/sentinel/demo/annotation/aop/service/ExceptionUtil.java View File

@@ -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());
}
}

+ 1
- 1
sentinel-demo/sentinel-demo-annotation-spring-aop/src/main/java/com/alibaba/csp/sentinel/demo/annotation/aop/service/TestServiceImpl.java View File

@@ -27,7 +27,7 @@ import org.springframework.stereotype.Service;
public class TestServiceImpl implements TestService { public class TestServiceImpl implements TestService {


@Override @Override
@SentinelResource("test")
@SentinelResource(value = "test", blockHandler = "handleException", blockHandlerClass = {ExceptionUtil.class})
public void test() { public void test() {
System.out.println("Test"); System.out.println("Test");
} }


+ 8
- 2
sentinel-extension/sentinel-annotation-aspectj/README.md View File

@@ -9,8 +9,14 @@ The `@SentinelResource` annotation indicates a resource definition, including:


- `value`: Resource name, required (cannot be empty) - `value`: Resource name, required (cannot be empty)
- `entryType`: Resource entry type (inbound or outbound), `EntryType.OUT` by default - `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: For example:




+ 6
- 0
sentinel-extension/sentinel-annotation-aspectj/pom.xml View File

@@ -32,6 +32,12 @@
<artifactId>aspectjweaver</artifactId> <artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version> <version>${aspectj.version}</version>
</dependency> </dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies> </dependencies>


</project> </project>

+ 8
- 6
sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/ResourceMetadataRegistry.java View File

@@ -22,36 +22,38 @@ import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.csp.sentinel.util.StringUtil; import com.alibaba.csp.sentinel.util.StringUtil;


/** /**
* Registry for resource configuration metadata (e.g. fallback method)
*
* @author Eric Zhao * @author Eric Zhao
*/ */
public final class ResourceMetadataRegistry {
final class ResourceMetadataRegistry {


private static final Map<String, MethodWrapper> FALLBACK_MAP = new ConcurrentHashMap<String, MethodWrapper>(); private static final Map<String, MethodWrapper> FALLBACK_MAP = new ConcurrentHashMap<String, MethodWrapper>();
private static final Map<String, MethodWrapper> BLOCK_HANDLER_MAP = new ConcurrentHashMap<String, MethodWrapper>(); private static final Map<String, MethodWrapper> BLOCK_HANDLER_MAP = new ConcurrentHashMap<String, MethodWrapper>();


public static MethodWrapper lookupFallback(Class<?> clazz, String name) {
static MethodWrapper lookupFallback(Class<?> clazz, String name) {
return FALLBACK_MAP.get(getKey(clazz, 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)); 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)) { if (clazz == null || StringUtil.isBlank(name)) {
throw new IllegalArgumentException("Bad argument"); throw new IllegalArgumentException("Bad argument");
} }
FALLBACK_MAP.put(getKey(clazz, name), MethodWrapper.wrap(method)); 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)) { if (clazz == null || StringUtil.isBlank(name)) {
throw new IllegalArgumentException("Bad argument"); throw new IllegalArgumentException("Bad argument");
} }
BLOCK_HANDLER_MAP.put(getKey(clazz, name), MethodWrapper.wrap(method)); 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); return String.format("%s:%s", clazz.getCanonicalName(), name);
} }
} }

+ 56
- 26
sentinel-extension/sentinel-annotation-aspectj/src/main/java/com/alibaba/csp/sentinel/annotation/aspectj/SentinelResourceAspect.java View File

@@ -16,6 +16,7 @@
package com.alibaba.csp.sentinel.annotation.aspectj; package com.alibaba.csp.sentinel.annotation.aspectj;


import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays; import java.util.Arrays;


import com.alibaba.csp.sentinel.Entry; 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.Aspect;
import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/** /**
* Aspect for methods with {@link SentinelResource} annotation. * Aspect for methods with {@link SentinelResource} annotation.
@@ -42,6 +45,8 @@ import org.aspectj.lang.reflect.MethodSignature;
@Aspect @Aspect
public class SentinelResourceAspect { public class SentinelResourceAspect {


private final Logger logger = LoggerFactory.getLogger(SentinelResourceAspect.class);

@Pointcut("@annotation(com.alibaba.csp.sentinel.annotation.SentinelResource)") @Pointcut("@annotation(com.alibaba.csp.sentinel.annotation.SentinelResource)")
public void sentinelResourceAnnotationPointcut() { public void sentinelResourceAnnotationPointcut() {
} }
@@ -84,10 +89,14 @@ public class SentinelResourceAspect {
} }
} }
// Execute block handler if configured. // Execute block handler if configured.
Method blockHandler = extractBlockHandlerMethod(pjp, annotation.blockHandler());
Method blockHandler = extractBlockHandlerMethod(pjp, annotation.blockHandler(), annotation.blockHandlerClass());
if (blockHandler != null) { if (blockHandler != null) {
// Construct args.
Object[] args = Arrays.copyOf(originArgs, originArgs.length + 1); Object[] args = Arrays.copyOf(originArgs, originArgs.length + 1);
args[args.length - 1] = ex; args[args.length - 1] = ex;
if (isStatic(blockHandler)) {
return blockHandler.invoke(null, args);
}
return blockHandler.invoke(pjp.getTarget(), args); return blockHandler.invoke(pjp.getTarget(), args);
} }
// If no block handler is present, then directly throw the exception. // 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) { private Method resolveFallbackInternal(ProceedingJoinPoint pjp, /*@NonNull*/ String name) {
Method originMethod = getMethod(pjp); Method originMethod = getMethod(pjp);
Class<?>[] parameterTypes = originMethod.getParameterTypes(); 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; 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); MethodWrapper m = ResourceMetadataRegistry.lookupBlockHandler(clazz, name);
if (m == null) { if (m == null) {
// First time, resolve the block handler. // First time, resolve the block handler.
Method method = resolveBlockHandlerInternal(pjp, name);
Method method = resolveBlockHandlerInternal(pjp, name, clazz, mustStatic);
// Cache the method instance. // Cache the method instance.
ResourceMetadataRegistry.updateBlockHandlerFor(clazz, name, method); ResourceMetadataRegistry.updateBlockHandlerFor(clazz, name, method);
return method; return method;
@@ -162,12 +159,45 @@ public class SentinelResourceAspect {
return m.getMethod(); 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); Method originMethod = getMethod(pjp);
Class<?>[] originList = originMethod.getParameterTypes(); Class<?>[] originList = originMethod.getParameterTypes();
Class<?>[] parameterTypes = Arrays.copyOf(originList, originList.length + 1); Class<?>[] parameterTypes = Arrays.copyOf(originList, originList.length + 1);
parameterTypes[parameterTypes.length - 1] = BlockException.class; 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) { private Method getMethod(ProceedingJoinPoint joinPoint) {


Loading…
Cancel
Save