Skip to content

Commit

Permalink
Add support for shared block handler
Browse files Browse the repository at this point in the history
- Update javadoc and document

Signed-off-by: Eric Zhao <sczyh16@gmail.com>
  • Loading branch information
sczyh30 committed Aug 8, 2018
1 parent d0970d5 commit b1cf30f
Show file tree
Hide file tree
Showing 8 changed files with 130 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
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)
Expand All @@ -46,6 +49,16 @@
*/
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
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,14 @@ public static void info(String detail, Throwable e) {
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);
}
}
Original file line number Diff line number Diff line change
@@ -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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
public class TestServiceImpl implements TestService {

@Override
@SentinelResource("test")
@SentinelResource(value = "test", blockHandler = "handleException", blockHandlerClass = {ExceptionUtil.class})
public void test() {
System.out.println("Test");
}
Expand Down
10 changes: 8 additions & 2 deletions sentinel-extension/sentinel-annotation-aspectj/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
6 changes: 6 additions & 0 deletions sentinel-extension/sentinel-annotation-aspectj/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>

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

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -22,36 +22,38 @@
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<String, MethodWrapper> FALLBACK_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));
}

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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -33,6 +34,8 @@
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.
Expand All @@ -42,6 +45,8 @@
@Aspect
public class SentinelResourceAspect {

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

@Pointcut("@annotation(com.alibaba.csp.sentinel.annotation.SentinelResource)")
public void sentinelResourceAnnotationPointcut() {
}
Expand Down Expand Up @@ -84,10 +89,14 @@ private Object handleBlockException(ProceedingJoinPoint pjp, SentinelResource an
}
}
// 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.
Expand Down Expand Up @@ -120,38 +129,26 @@ private Method extractFallbackMethod(ProceedingJoinPoint pjp, String fallbackNam
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;
Expand All @@ -162,12 +159,45 @@ private Method extractBlockHandlerMethod(ProceedingJoinPoint pjp, String name) {
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) {
Expand Down

0 comments on commit b1cf30f

Please sign in to comment.