现在有这样一种常见,系统中有一个接口,该接口执行的方法忽快忽慢,因此你需要去统计改方法的执行时间。刚开始你的代码可能如下:

          long start = System.currentTimeMillis();
somemethod();
long end = System.currentTimeMillis();
System.out.println(end-start);

这个方式能够打印方法执行的时间,可是疑问来了,如果系统中很多方法都需要计算时间,都需要重复这样的代码?这个时候,你可以考虑注解,通过aop去计时。

在项目中添加如下依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

  定义一个注解MethodStats,所有加上此注解的方法可以打印方法执行的时间。

package com.example.demo;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodStats {
}

  定义一个拦截类,通过此拦截类,可以统计有注解的方法的执行时间。

package com.example.demo;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component; @Aspect
@Component
public class TimeLogger
{
Logger logger = LoggerFactory.getLogger(getClass()); @Around("@annotation(com.example.demo.MethodStats)")
public Object log(ProceedingJoinPoint point) throws Throwable
{
long start = System.currentTimeMillis();
Object result = point.proceed();
logger.info("className={}, methodName={}, timeMs={},threadId={}",new Object[]{
MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName(),
MethodSignature.class.cast(point.getSignature()).getMethod().getName(),
System.currentTimeMillis() - start,
Thread.currentThread().getId()}
);
return result;
}
}

  下面是一个测试:

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HelloController { // 防在这里可以拦截
@GetMapping("/")
@MethodStats
public String hello2() {
return "hello2";
} }

  现在假设,我们需要方法必须在一定时间内执行完,如果没有执行完强制返回,我们现在就需要给注解添加一个时间的变量。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodStats {
public int time() default -1;
}

 相应的拦截器的方法做如下处理:

package com.example.demo;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import javax.rmi.CORBA.Tie; import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component; @Aspect
@Component
public class TimeLogger {
Logger logger = LoggerFactory.getLogger(getClass()); @Around("@annotation(com.example.demo.MethodStats)")
public Object log(ProceedingJoinPoint point) throws Throwable {
long start = System.currentTimeMillis(); int time = MethodSignature.class.cast(point.getSignature()).getMethod().getAnnotation(MethodStats.class).time(); if (time > 0) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Object> future = executor.submit(new Callable<Object>() {
public Object call() throws Exception {
Object result = null;
try {
result = point.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
});
try {
future.get(time, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
// do something or log it
} finally {
future.cancel(true);
logger.info("cancel");
} } else {
Object result = point.proceed();
logger.info("className={}, methodName={}, timeMs={},threadId={}",
new Object[] { MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName(),
MethodSignature.class.cast(point.getSignature()).getMethod().getName(),
System.currentTimeMillis() - start, Thread.currentThread().getId() });
return result;
}
return null;
}
}

  

主要思路使用Future去控制方法的执行时间,上述样例仅供学习测试,如果在线上环境,请使用hystrix,hystrix提供了晚上的failback。需要特别注意的是,spring 的事务提供了timeout的注解,可以控制事务的执行时间。

ARTS打卡计划第二周-Share-使用java注解对方法计时的更多相关文章

  1. ARTS打卡计划第二周

    Algorithms: https://leetcode-cn.com/problems/3sum/ 算法是先排序,然后按照两个数和两边逼中,考虑去重. Review: https://www.inf ...

  2. ARTS打卡计划第二周-Review

    本周review的文章是:https://medium.com/@hakibenita/optimizing-django-admin-paginator-53c4eb6bfca3 改篇文章的题目是: ...

  3. ARTS打卡计划第二周-Tips-mysql-binlog-connector-java的使用

    最近发现一个挺不错的框架mysql-binlog-connector-java,可以实时监控binlog的变化. 首先检查mysql的binlog是否开启,在开启的情况下: 引入依赖 <depe ...

  4. ARTS打卡计划第二周-Algorithm

    665. 非递减数列  https://leetcode-cn.com/problems/non-decreasing-array/ 给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元 ...

  5. ARTS打卡计划第九周

    Algorithms: https://leetcode-cn.com/problems/merge-two-sorted-lists/submissions/ 合并两个链表 Review:  “Pu ...

  6. ARTS打卡计划第一周

    Algorithms: https://leetcode-cn.com/problems/two-sum/ Review: https://www.infoq.cn/article/EafgGJEtq ...

  7. ARTS打卡计划第一周-Share-系统字典模块的设计

    在软件开发的过程,经常有一些类型的字段信息:性别.学历.职级.车辆类别.公司类型.结算类型等.这些字段有2个特征:1是字段可选的类型是有限,2是字段可能会变化,我们把这种字段描述为字段字段.  本篇文 ...

  8. ARTS打卡计划第一周-Tips-ControllerAdvice的使用

    通常在开发具体项目过程中我们可能会面临如下问题: 统一所有的json返回结果 统一处理所有controller中的异常,并且给不同异常不同的返回状态值 统一对返回的接口做数据校验或者加密,防止篡改 在 ...

  9. ARTS打卡计划第一周-Review

    本周分享的文章来自于medium的 Testing Best Practices for Java + Spring Apps 这个文章主要讲的是java测试的一些最佳实践 1.避免函数返回void, ...

随机推荐

  1. pyhanlp:hanlp的python接口

    HanLP的Python接口,支持自动下载与升级HanLP,兼容py2.py3. 安装 pip install pyhanlp 使用命令hanlp来验证安装,如因网络等原因自动安装失败,可参考手动配置 ...

  2. DNS子域授权

    DNS子域授权 当一个域很大时,而且还有上,下层关系,如果所有的记录变更都由某一台服务器来管理的话,那将会是什么样子?就好比一个公司的总经理直接管理公司1000个人的所有事项,恐怕会被累死.所以会在总 ...

  3. siftflow-fcn32s训练及预测

    一.说明 SIFT Flow 是一个标注的语义分割的数据集,有两个label,一个是语义分类(33类),另一个是场景标签(3类). Semantic and geometric segmentatio ...

  4. 基于scrapy源码实现的自定义微型异步爬虫框架

    一.scrapy原理 Scrapy 使用了 Twisted异步网络库来处理网络通讯.整体架构大致如下 Scrapy主要包括了以下组件: 引擎(Scrapy)用来处理整个系统的数据流处理, 触发事务(框 ...

  5. 新建服务器出现错误 Peer authentication failed for user "postgres" 的解决办法

    用pgadmin3 新建服务器出现错误 Peer authentication failed for user "postgres" 在stackoverflow上找到答案,出现此 ...

  6. java 类的初始化顺序

    有父类 1. 父类static成员变量 2. 父类static块 3. 父类非static成员 4. 父类非static块 5. 父类构造方法 子类,也按照1-5顺序执行 无父类 1. static成 ...

  7. 洛谷P1039 侦探推理(模拟)

    侦探推理 题目描述 明明同学最近迷上了侦探漫画<柯南>并沉醉于推理游戏之中,于是他召集了一群同学玩推理游戏.游戏的内容是这样的,明明的同学们先商量好由其中的一个人充当罪犯(在明明不知情的情 ...

  8. Centos6.9部署vnc

    Centos部署vnc   [root@etl ~]# vncserver -kill :1 命令: service vncserver restart chkconfig --list vncser ...

  9. note 5 二分法求平方根,素数,回文数

    +二分法求平方根 x = float(raw_input('Enter the number')) low = 0 high = x guess = (low + high ) / 2 if x &l ...

  10. jmeter向ActiveMQ发送消息_广播/订阅(Topics 队列)

    问题描述:测试中需要模拟大量设备的消息上报到平台,但是实际测试中没有那么多设备,所以采取用jmeter直接往ActiveMQ模拟发送设备消息 解决思路:获取平台采取的是Queues还是Topics : ...