需求:任意业务层接口执行均可显示其执行效率(执行时长)
分析:
1、业务功能:业务层接口执行前后分别记录时间,求差值得到执行效率
2、通知类型选择前后均可以增强的类型——环绕通知
代码实现:
环境主要是Spring整合MBatis和整合JUnit的一些环境,此案例主要是用AOP测量业务层接口万次执行效率
AccountServiceTestCase测试类:测试查询一次和查询全部效果
import com.itheima.config.SpringConfig;
import com.itheima.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTestCase {
@Autowired
private AccountService accountService;
@Test
public void testFindById(){
Account ac = accountService.findById(2);
System.out.println(ac);
}
@Test
public void testFindAll(){
List<Account> all = accountService.findAll();
System.out.println(all);
}
}
执行结果:
SpringConfig配置类:开启注解开发AOP功能
@EnableAspectJAutoProxy
public class SpringConfig {
}
创建AOP包,定义通知类受Spring容器管理,并定义当前类为切面类,设置切入点,并且设置环绕通知,在原始操作的运行前后记录执行时间,获取签名对象,通过签名获取执行类型(接口名)和获取执行操作名称(方法名)。
ProjectAdvice类:测量业务层接口执行效率(万次核心代码执行效率)
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class ProjectAdvice {
//匹配业务层的所有方法
@Pointcut("execution(* com.itheima.service.*Service.*(..))")
private void servicePt(){}
//设置环绕通知,在原始操作的运行前后记录执行时间
@Around("ProjectAdvice.servicePt()")
public void runSpeed(ProceedingJoinPoint pjp) throws Throwable {
//获取执行的签名对象
Signature signature = pjp.getSignature();
//通过签名获取执行类型(接口名)
String className = signature.getDeclaringTypeName();
//通过签名获取执行操作名称(方法名)
String methodName = signature.getName();
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
pjp.proceed();
}
long end = System.currentTimeMillis();
System.out.println("万次执行:"+ className+"."+methodName+"---->" +(end-start) + "ms");
}
}
执行结果:
说明:
当前测试的接口执行效率仅仅是一个理论值,并不是一次完整的执行过程。
真正的一个业务执行还有表现层,还有前端的那些东西,客户拿到的信息最终时长和这个案例测出来的时长偏差较大,完全是两码事,此案例只是模拟的测了一下业务层接口。