반응형
Recent Posts
Recent Comments
관리 메뉴

개발잡부

[AOP] 메소드 실행시간 측정 본문

JAVA/AOP

[AOP] 메소드 실행시간 측정

닉의네임 2022. 4. 23. 17:25
반응형

Annotation

package com.bbongdoo.doo.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Timer {
}

 

Aspect

package com.bbongdoo.doo.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Aspect
@Component
public class TimerAop {
    @Pointcut("@annotation(com.bbongdoo.doo.annotation.Timer)")
    private void enableTimer() {}


    @Around("enableTimer()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        var stopWatch = new StopWatch();
        stopWatch.start();

        Object result = joinPoint.proceed();

        stopWatch.stop();

        System.out.println("total time is : " + stopWatch.getTotalTimeMillis());

        return result;
    }
}

사용

서비스에 붙여주자

package com.bbongdoo.doo.service;


import com.bbongdoo.doo.annotation.Timer;
import com.bbongdoo.doo.domain.Keywords;
import com.bbongdoo.doo.domain.KeywordsRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class KeywordsService {

    private final KeywordsRepository keywordsRepository;
    private List<Keywords> keywords;

    @Timer
    @Transactional
    public void post(List<String> keywordList) {
        keywords = new ArrayList<>();
        keywordList.stream().forEach(x -> {
            keywords.add(new Keywords(x, "Y"));
        });
        keywordsRepository.saveAll(keywords);
    }

    @Timer
    @Transactional
    public List<Keywords> get() {
        return keywordsRepository.findAll();
    }

    @Timer
    @Transactional
    public List<Keywords> getKeywordsByUse(String use) {
        return keywordsRepository.findAllByUseYn(use);
    }

    @Timer
    @Transactional
    public List<Keywords> getKeywordsByKeyword(String keyword) {
        return keywordsRepository.findAllByKeyword(keyword);
    }
}
반응형
Comments