Spring案例:测量业务层接口万次执行效率

需求:任意业务层接口执行均可显示其执行效率(执行时长)

分析:

1、业务功能:业务层接口执行前后分别记录时间,求差值得到执行效率

2、通知类型选择前后均可以增强的类型——环绕通知

代码实现:

环境主要是Spring整合MBatis和整合JUnit的一些环境,此案例主要是用AOP测量业务层接口万次执行效率

(6条消息) Spring整合MyBatis、整合JUnit_夏志121的博客-CSDN博客icon-default.png?t=M5H6https://blog.csdn.net/m0_61961937/article/details/125303698?spm=1001.2014.3001.5501

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");
    }
}

执行结果:

说明:

当前测试的接口执行效率仅仅是一个理论值,并不是一次完整的执行过程。

真正的一个业务执行还有表现层,还有前端的那些东西,客户拿到的信息最终时长和这个案例测出来的时长偏差较大,完全是两码事,此案例只是模拟的测了一下业务层接口。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏志121

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值