下面列出了org.aspectj.lang.annotation.AfterThrowing#org.aspectj.lang.Signature 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Before("pointcut()")
public void doVerifyBefore(JoinPoint joinPoint) {
// 1. 参数校验
Signature signature = joinPoint.getSignature();
// 2. 开发环境-打印日志
String ip = ServletUtils.getClientIP();
String uri = request.getRequestURI();
// UserDTO user_info = null;
// if (!uri.startsWith("/open")) {
// user_info = UserUtils.getUser(request, redis, UserDTO.class);
// }
log.info("ip={}", ip);
log.info("uri={}", uri);
// log.info("user_info={}", user_info);
log.info("method={}", request.getMethod());
log.info("class_method={}", signature.getDeclaringTypeName() + "." + signature.getName() + "()");
}
private static Annotation getAnnotation(final Signature signature,
final Class<? extends Annotation> annotationClass) {
if (signature instanceof ConstructorSignature) {
final Constructor<?> ctor = ConstructorSignature.class.cast(signature)
.getConstructor();
return ctor.getAnnotation(annotationClass);
} else if (signature instanceof MethodSignature) {
return MethodSignature.class.cast(signature)
.getMethod()
.getAnnotation(annotationClass);
} else if (signature instanceof FieldSignature) {
return FieldSignature.class.cast(signature)
.getField()
.getAnnotation(annotationClass);
}
throw new RuntimeException(
"Unsupported signature type " + signature.getClass().getName()
);
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
if (aopLogInterface != null) {
aopLogInterface.before(joinPoint);
}
// 接收到请求,记录请求内容
IS_LOG.set(ExtConfigBean.getInstance().isConsoleLogReqResponse());
Signature signature = joinPoint.getSignature();
if (signature instanceof MethodSignature) {
MethodSignature methodSignature = (MethodSignature) signature;
ResponseBody responseBody = methodSignature.getMethod().getAnnotation(ResponseBody.class);
if (responseBody == null) {
RestController restController = joinPoint.getTarget().getClass().getAnnotation(RestController.class);
if (restController == null) {
IS_LOG.set(false);
}
}
}
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
LogMenthodName logMenthodName = method.getAnnotation(LogMenthodName.class);
String time = (System.currentTimeMillis() - startTime.get()) + "ms";
if (method.isAnnotationPresent(LogMenthodName.class)) {
String token = request.getHeader(AuthSign.token);
Long id = AuthSign.getUserId(token);
if (id != 0) {
logAdminAgent.setReturnParam(Arrays.asList(ret).toString());
logAdminAgent.setTime(time);
logAdminAgent.setOperatorId(id);
logAdminAgent.setOperatorPlatform(LogAdminAgentAppEnum.ANDROID_SYS.getSystem());
logAdminAgent.setLoginFacility(HttpRequestUtil.getSystemDevice(request));
logAdminAgentService.save(logAdminAgent);
}
}
// 处理完请求,返回内容
logger.info("返回内容: " + Arrays.asList(ret));
logger.info("耗时 : " + time);
startTime.remove();
}
@Around("servicePointcut()")
public Object doServiceAround(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
Signature signature = thisJoinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
final Method targetMethod = methodSignature.getMethod();
OptimisticLock optimisticLock = targetMethod.getAnnotation(OptimisticLock.class);
if (optimisticLock == null) {
throw new RuntimeException("乐观锁aop异常");
}
Class<? extends Exception>[] catchTypes = optimisticLock.catchType();
if (catchTypes == null || catchTypes.length == 0) {
throw new RuntimeException("乐观锁aop异常");
}
int retry = optimisticLock.retry();
Object object = tryServiceProceed(thisJoinPoint, catchTypes, retry);
return object;
}
@Around("cacheAspect()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
Object result = null;
try {
result = joinPoint.proceed();
} catch (Throwable throwable) {
//有CacheException注解的方法需要抛出异常
if (method.isAnnotationPresent(CacheException.class)) {
throw throwable;
} else {
LOGGER.error(throwable.getMessage());
}
}
return result;
}
private Object execute(Class<? extends LockableStrategy> clazz, ProceedingJoinPoint point, Signature signature) throws Throwable {
Method method = ((MethodSignature) signature).getMethod();
// 获取锁策略
LockableStrategy strategy = strategies.get(method);
if (strategy == null) {
synchronized (method) {
if (strategy == null) {
strategy = ReflectionUtility.getInstance(clazz, method);
strategies.put(method, strategy);
}
}
}
Object[] arguments = point.getArgs();
try (Lockable lock = strategy.getLock(arguments)) {
lock.open();
return point.proceed(arguments);
}
}
/**
* 日志输出到文件, 提供给日志切面
* @param joinPoint
* @param ex
*/
public static void logToFile(JoinPoint joinPoint, Throwable ex) {
//出错行
int lineNumber = ex.getStackTrace()[0].getLineNumber();
//方法签名
Signature signature = joinPoint.getSignature();
//参数
Object[] args = joinPoint.getArgs();
StringBuilder builder = new StringBuilder();
if (args.length > 0) {
for (Object o : args) {
builder.append(o);
}
}
log.error("方法:" + signature + " | " + "参数:" + builder.toString() +
" | " + "错误行:" + lineNumber + " | " + "时间:" + new Date() +
" | " + "异常内容:" + ex.toString()
);
}
@Around("monitored()")
public Object requestMapping(final ProceedingJoinPoint pcp) throws Throwable {
Signature signature = pcp.getSignature();
if (signature instanceof MethodSignature) {
Method method = ((MethodSignature) signature).getMethod();
MethodProfiling annotation = AnnotationUtils.findAnnotation(method, MethodProfiling.class);
if (annotation == null) {
annotation = AnnotationUtils.findAnnotation(pcp.getTarget().getClass(), MethodProfiling.class);
}
if (annotation != null) {
return traceMethodCall(pcp, annotation.logCallStatistics(), annotation.logMethodCall(), annotation.maxToStringLength());
}
}
return traceMethodCall(pcp);
}
/**
* This is an advice which will be used after the construction of an object.
*
* @param thisObject
* @param jp
* The static information about this joint point.
*/
// HINT: This may be logged multiple times due to super constructor calls...
@AfterReturning("monitoredConstructor() && this(thisObject) && notWithinKieker()")
public void afterConstruction(final Object thisObject, final JoinPoint.StaticPart jp) {
if (!CTRLINST.isMonitoringEnabled()) {
return;
}
final Signature signature = jp.getSignature();
if (!CTRLINST.isProbeActivated(this.signatureToLongString(signature))) {
return;
}
// common fields
TraceMetadata trace = TRACEREGISTRY.getTrace();
final boolean newTrace = trace == null;
if (newTrace) {
trace = TRACEREGISTRY.registerTrace();
CTRLINST.newMonitoringRecord(trace);
}
final ConstructionEvent crecord = new ConstructionEvent(TIME.getTime(), trace.getTraceId(), trace.getNextOrderId(), signature.getDeclaringTypeName(),
System.identityHashCode(thisObject));
CTRLINST.newMonitoringRecord(crecord);
}
/**
* 获取连接点的制定类型的注解
*
* @param joinPoint 连接点
* @param clazz 注解类
*
* @return 注解
*/
public static Annotation getAnnotation(ProceedingJoinPoint joinPoint, Class clazz) {
try {
// 拦截的对象
Object object = joinPoint.getTarget();
Signature signature = joinPoint.getSignature();
// 拦截方法名
String methodName = signature.getName();
Class[] parameterTypes = ((MethodSignature) signature).getMethod().getParameterTypes();
try {
// 反射目标方法
Method method = object.getClass().getDeclaredMethod(methodName, parameterTypes);
// 获取注解
return method.getDeclaredAnnotation(clazz);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
/**
* 前置操作,拦截具体请求,获取header里的数据源id,设置线程变量里,用于后续切换数据源
*/
@Before("datasourcePointcut()")
public void doBefore(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
// 排除不可切换数据源的方法
DefaultDatasource annotation = method.getAnnotation(DefaultDatasource.class);
if (null != annotation) {
DatasourceConfigContextHolder.setDefaultDatasource();
} else {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = attributes.getRequest();
String configIdInHeader = request.getHeader("Datasource-Config-Id");
if (StringUtils.hasText(configIdInHeader)) {
long configId = Long.parseLong(configIdInHeader);
DatasourceConfigContextHolder.setCurrentDatasourceConfig(configId);
} else {
DatasourceConfigContextHolder.setDefaultDatasource();
}
}
}
/**
* Monitor the elapsed time of method on controller layer, in
* order to detect performance problems as soon as possible.
* If elapsed time > 1 s, log it as an error. Otherwise, log it
* as an info.
*/
@Around("controllerLayer()")
public Object monitorElapsedTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// Timing the method in controller layer
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object result = proceedingJoinPoint.proceed();
stopWatch.stop();
// Log the elapsed time
double elapsedTime = stopWatch.getTime() / 1000.0;
Signature signature = proceedingJoinPoint.getSignature();
String infoString = "[" + signature.toShortString() + "][Elapsed time: " + elapsedTime + " s]";
if (elapsedTime > 1) {
log.error(infoString + "[Note that it's time consuming!]");
} else {
log.info(infoString);
}
// Return the result
return result;
}
/**
* Save invocation/execution time associated with the method to StatsD in the format: com.mypackage.myMethod
*/
@Override
public void stop(TimerContext context) {
Signature sig = context.getJoinPoint().getSignature();
String className = sig.getDeclaringTypeName(); // package name: com.my.package
String methodName = sig.getName(); // method name: myMethod
String label = className + "." + methodName;
statsdClient.recordExecutionTime(label, context.stop());
}
/**
* 是否存在注解,如果存在就获取
*/
private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
{
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null)
{
return method.getAnnotation(Log.class);
}
return null;
}
/**
* 是否存在注解,如果存在就获取
*/
private DataScope getAnnotationLog(JoinPoint joinPoint)
{
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null)
{
return method.getAnnotation(DataScope.class);
}
return null;
}
@Around("call(* com.optimize.performance.PerformanceApp.**(..))")
public void getTime(ProceedingJoinPoint joinPoint) {
// 签名
Signature signature = joinPoint.getSignature();
String name = signature.toShortString();
long time = System.currentTimeMillis();
try {
joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
// LogUtils.i(name + " cost " + (System.currentTimeMillis() - time));
}
/**
* This is an advice used around calls from static elements to constructors.
*
* @param thisJoinPoint
* The joint point of the callee.
* @param thisEnclosingJoinPoint
* The joint point of the caller.
*
* @return The result of {@code proceed method} of the given joint point.
*
* @throws Throwable
*/
@Around("monitoredConstructor() && !this(java.lang.Object) && notWithinKieker()")
public Object static2constructor(final ProceedingJoinPoint thisJoinPoint, final EnclosingStaticPart thisEnclosingJoinPoint)
throws Throwable { // NOCS
if (!CTRLINST.isMonitoringEnabled()) {
return thisJoinPoint.proceed();
}
final Signature calleeSig = thisJoinPoint.getSignature();
final String callee = this.signatureToLongString(calleeSig);
if (!CTRLINST.isProbeActivated(callee)) {
return thisJoinPoint.proceed();
}
// common fields
TraceMetadata trace = TRACEREGISTRY.getTrace();
final boolean newTrace = trace == null;
if (newTrace) {
trace = TRACEREGISTRY.registerTrace();
CTRLINST.newMonitoringRecord(trace);
}
final long traceId = trace.getTraceId();
// caller
final Signature callerSig = thisEnclosingJoinPoint.getSignature();
final String caller = this.signatureToLongString(callerSig);
final String callerClazz = callerSig.getDeclaringTypeName();
// callee
final String calleeClazz = calleeSig.getDeclaringTypeName();
// measure before call
CTRLINST.newMonitoringRecord(new CallConstructorEvent(TIME.getTime(), traceId, trace.getNextOrderId(),
caller, callerClazz, callee, calleeClazz));
// call of the called method
final Object retval;
try {
retval = thisJoinPoint.proceed();
} finally {
if (newTrace) { // close the trace
TRACEREGISTRY.unregisterTrace();
}
}
return retval;
}
@Around("pointcut() && @annotation(limiter)")
public Object around(ProceedingJoinPoint pjp, Limiter limiter) throws Throwable {
cn.yueshutong.core.limiter.RateLimiter rateLimiter = RateLimiterObserver.getMap().get(limiter.value());
if (rateLimiter.tryAcquire()) {
return pjp.proceed();
}
Signature sig = pjp.getSignature();
if (!(sig instanceof MethodSignature)) {
throw new IllegalArgumentException("This annotation can only be used in methods.");
}
MethodSignature msg = (MethodSignature) sig;
Object target = pjp.getTarget();
Method fallback = target.getClass().getMethod(limiter.fallback(), msg.getParameterTypes());
return fallback.invoke(target,pjp.getArgs());
}
/**
* This advice is used around static operations.
*
* @param thisJoinPoint
* The joint point of the advice.
*
* @return The return value of the joint point's {@code proceed} method.
*
* @throws Throwable
*/
@Around("monitoredOperation() && !this(java.lang.Object) && notWithinKieker()")
public Object staticOperation(final ProceedingJoinPoint thisJoinPoint) throws Throwable { // NOCS (Throwable)
if (!CTRLINST.isMonitoringEnabled()) {
return thisJoinPoint.proceed();
}
final Signature sig = thisJoinPoint.getSignature();
final String operationSignature = this.signatureToLongString(sig);
if (!CTRLINST.isProbeActivated(operationSignature)) {
return thisJoinPoint.proceed();
}
// common fields
TraceMetadata trace = TRACEREGISTRY.getTrace();
final boolean newTrace = trace == null;
if (newTrace) {
trace = TRACEREGISTRY.registerTrace();
CTRLINST.newMonitoringRecord(trace);
}
final long traceId = trace.getTraceId();
final String clazz = sig.getDeclaringTypeName();
// measure before execution
CTRLINST.newMonitoringRecord(new BeforeOperationObjectEvent(TIME.getTime(), traceId, trace.getNextOrderId(), operationSignature, clazz, 0));
// execution of the called method
final Object retval;
try {
retval = thisJoinPoint.proceed();
} catch (final Throwable th) { // NOPMD NOCS (catch throw might ok here)
// measure after failed execution
CTRLINST.newMonitoringRecord(new AfterOperationFailedObjectEvent(TIME.getTime(), traceId, trace.getNextOrderId(), operationSignature, clazz,
th.toString(), 0));
throw th;
} finally {
if (newTrace) { // close the trace
TRACEREGISTRY.unregisterTrace();
}
}
// measure after successful execution
CTRLINST.newMonitoringRecord(new AfterOperationObjectEvent(TIME.getTime(), traceId, trace.getNextOrderId(), operationSignature, clazz, 0));
return retval;
}
/**
* 获取当前方法信息
*
* @param point 切点
* @return 方法
*/
private Method getCurrentMethod(ProceedingJoinPoint point) {
try {
Signature sig = point.getSignature();
MethodSignature msig = (MethodSignature) sig;
Object target = point.getTarget();
return target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
} catch (NoSuchMethodException e) {
throw new RetryException(e);
}
}
private OperateLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
OperateLog classAnnotation = AnnotationUtils.findAnnotation(method.getDeclaringClass(), OperateLog.class);
if (method != null) {
return classAnnotation;
}
return null;
}
/**
* swagger API
*
* @param joinPoint
* @return
* @throws Exception
*/
private Api getApi(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
Api classAnnotation = AnnotationUtils.findAnnotation(method.getDeclaringClass(), Api.class);
if (method != null) {
return classAnnotation;
}
return null;
}
/**
* swagger ApiOperation
*
* @param joinPoint
* @return
* @throws Exception
*/
private ApiOperation getApiOperation(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null) {
return method.getAnnotation(ApiOperation.class);
}
return null;
}
@Around("webLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
//获取当前请求对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//记录请求信息(通过Logstash传入Elasticsearch)
WebLog webLog = new WebLog();
Object result = joinPoint.proceed();
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method.isAnnotationPresent(ApiOperation.class)) {
ApiOperation log = method.getAnnotation(ApiOperation.class);
webLog.setDescription(log.value());
}
long endTime = System.currentTimeMillis();
String urlStr = request.getRequestURL().toString();
webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
webLog.setIp(request.getRemoteUser());
webLog.setMethod(request.getMethod());
webLog.setParameter(getParameter(method, joinPoint.getArgs()));
webLog.setResult(result);
webLog.setSpendTime((int) (endTime - startTime));
webLog.setStartTime(startTime);
webLog.setUri(request.getRequestURI());
webLog.setUrl(request.getRequestURL().toString());
Map<String, Object> logMap = new HashMap<>();
logMap.put("url", webLog.getUrl());
logMap.put("method", webLog.getMethod());
logMap.put("parameter", webLog.getParameter());
logMap.put("spendTime", webLog.getSpendTime());
logMap.put("description", webLog.getDescription());
// LOGGER.info("{}", JSONUtil.parse(webLog));
LOGGER.info(Markers.appendEntries(logMap), JSONUtil.parse(webLog).toString());
return result;
}
private void saveKnoxShellTableCall(JoinPoint joinPoint, long builderId) {
final Signature signature = joinPoint.getSignature();
final boolean builderMethod = KNOX_SHELL_TYPE.equals(((MethodSignature) signature).getReturnType().getCanonicalName());
final Map<Object, Class<?>> params = new HashMap<>();
Arrays.stream(joinPoint.getArgs()).forEach(param -> params.put(param, param.getClass()));
KnoxShellTableCallHistory.getInstance().saveCall(builderId, new KnoxShellTableCall(signature.getDeclaringTypeName(), signature.getName(), builderMethod, params));
}
@Around("webLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
//获取当前请求对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//记录请求信息
WebLog webLog = new WebLog();
Object result = joinPoint.proceed();
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method.isAnnotationPresent(ApiOperation.class)) {
ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
webLog.setDescription(apiOperation.value());
}
long endTime = System.currentTimeMillis();
String urlStr = request.getRequestURL().toString();
webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
webLog.setIp(request.getRemoteUser());
webLog.setMethod(request.getMethod());
webLog.setParameter(getParameter(method, joinPoint.getArgs()));
webLog.setResult(result);
webLog.setSpendTime((int) (endTime - startTime));
webLog.setStartTime(startTime);
webLog.setUri(request.getRequestURI());
webLog.setUrl(request.getRequestURL().toString());
LOGGER.info("{}", JSONUtil.parse(webLog));
return result;
}
/**
* Description: <br>
*
* @author 王伟<br>
* @taskId <br>
* @param thisJoinPoint
* @return Object
* @throws Throwable <br>
*/
@Around("cacheLock()")
public Object invoke(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
Signature sig = thisJoinPoint.getSignature();
if (sig instanceof MethodSignature) {
MethodSignature msig = (MethodSignature) sig;
Object target = thisJoinPoint.getTarget();
Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
CacheLock cacheLock = AnnotationUtils.findAnnotation(currentMethod, CacheLock.class);
if (cacheLock != null) {
// 新建一个锁
RedisLock lock = new RedisLock(
cacheLock.value() + KeyUtil.getLockKey(cacheLock.key(), currentMethod, thisJoinPoint.getArgs()));
// 加锁
boolean result = lock.lock(
cacheLock.timeOut() > cacheLock.expireTime() ? cacheLock.timeOut() : cacheLock.expireTime(),
cacheLock.expireTime());
if (!result) {
throw new ServiceException(ErrorCodeDef.GET_CACHE_LOCK_ERROR, lock);
}
try {
// 加锁成功,执行方法
return thisJoinPoint.proceed();
}
finally {
lock.unlock();
}
}
}
return thisJoinPoint.proceed();
}
/**
* 是否存在注解,如果存在就获取
*/
private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
{
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null)
{
return method.getAnnotation(Log.class);
}
return null;
}
@Test
public void testActiveJobs() throws Throwable {
ProceedingJoinPoint pjp = mock(ProceedingJoinPoint.class);
Signature signature = mock(Signature.class);
when(pjp.getSignature()).thenReturn(signature);
when(pjp.getTarget()).thenReturn(this);
when(signature.getDeclaringType()).thenReturn(ScheduledJob.class);
jobs.aroundScheduledJob(pjp);
MockAsyncResponse<String> response = new MockAsyncResponse<>();
active.activeJobs(response);
assertThat(convert(response.response()).get("events"), is(1));
}