Spring AOP 性能监控切面、异常处理切面、请求参数校验切面

程序性能监控切面

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component
@Aspect
public class ServiceExceptionHandleAspect {
    private static final Logger logger = LoggerFactory.getLogger(ServiceExceptionHandleAspect.class);

    @Pointcut("@annotation(com.xxxxx.aspect.annotation.AnnotationForService)")
    public void serviceMethodPointcut() {
    }

    @AfterThrowing(pointcut = "serviceMethodPointcut()", throwing = "t")
    public void handleServiceMethodException(JoinPoint joinPoint, Throwable t) {
        String methodName = joinPoint.getSignature().toLongString();
        logger.warn(methodName + ":" + ExceptionUtils.getMessage(t));
    }
}

程序异常处理切面

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class RestServiceExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(RestServiceExceptionHandler.class);

    @Pointcut("@annotation(com.xxxxx.aspect.annotation.AnnotationForQryMethod)")
    public void qryMethodPointcut() {
    }

    @Pointcut("@annotation(com.xxxxxx.aspect.annotation.AnnotationForDelMethod)")
    public void delMethodPointcut() {
    }

    @AfterThrowing(pointcut = "qryMethodPointcut()", throwing = "t")
    public void handleQryMethodException(JoinPoint joinPoint, Throwable t) {
        String methodName = joinPoint.getSignature().toLongString();
        logger.warn(methodName + ":" + ExceptionUtils.getExceptionStackTrace(t));
    }

    @Around("qryMethodPointcut()")
    public Object handleQryMethodException(ProceedingJoinPoint joinPoint) {
        try {
            return joinPoint.proceed();
        } catch (Throwable t) {
            System.out.println(ExceptionUtils.getExceptionStackTrace(t));
            logger.warn(ExceptionUtils.getExceptionStackTrace(t));
            return ResultMessageUtil.getErrorResultMessage(new ResultMessage(),
                    ErrorNumConsts.QUERY_ERROR, "查询失败,请再次尝试");
        }
    }

    @Around("delMethodPointcut()")
    public Object handleDelMethodException(ProceedingJoinPoint joinPoint) {
        try {
            return joinPoint.proceed();
        } catch (Throwable t) {
            System.out.println(ExceptionUtils.getExceptionStackTrace(t));
            logger.warn(ExceptionUtils.getExceptionStackTrace(t));
            return ResultMessageUtil.getErrorResultMessage(new ResultMessage(),
                    ErrorNumConsts.DELETE_ERROR, "删除失败,请再次尝试");
        }
    }

}

校验 HTTP 请求参数切面

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.Collections;


@Aspect
@Component
public class RestServiceValidReqAndHandleExc {
    private static final Logger logger = LoggerFactory.getLogger(RestServiceValidReqAndHandleExc.class);

    @Pointcut("@annotation(com.xxxx.aspect.annotation.AnnForValidReqAndHandleExc)")
    public void parseRequestPointcut() {
    }

    @Around("parseRequestPointcut()")
    public Object parseHttpRequest(ProceedingJoinPoint joinPoint) {
        HttpServletRequest request = (HttpServletRequest) joinPoint.getArgs()[0];
        ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest(request);
        try {
            wrappedRequest.setCharacterEncoding("utf-8");
            String bodyStr = HttpServletRequestUtil.readHttpServletRequestBody(wrappedRequest);
            if (StringUtils.isEmpty(bodyStr))
                return ResultMessageUtil.getErrorResultMessage(new ResultMessage(), ErrorNumConsts.PARAM_ERROR,
                        "请求数据不能为空!");
        } catch (Exception e) {
            System.out.println(ExceptionUtils.getExceptionStackTrace(e));
            return ResultMessageUtil.getErrorResultMessage(new ResultMessage(), ErrorNumConsts.PARAM_ERROR,
                    "解析请求数据错误!");
        }
        try {
            wrappedRequest.resetInputStream();
            Object[] args = Collections.singletonList(wrappedRequest).toArray();
            return joinPoint.proceed(args);
        } catch (Throwable t) {
            logger.warn(ExceptionUtils.getExceptionStackTrace(t));
            return ResultMessageUtil.getErrorResultMessage(new ResultMessage(), ErrorNumConsts.OPERATION_ERROR,
                    "操作失败,请再次尝试!");
        }
    }

    private static class ResettableStreamHttpServletRequest extends
            HttpServletRequestWrapper {

        private byte[] rawData;
        private HttpServletRequest request;
        private ResettableServletInputStream servletStream;

        ResettableStreamHttpServletRequest(HttpServletRequest request) {
            super(request);
            this.request = request;
            this.servletStream = new ResettableServletInputStream();
        }


        void resetInputStream() {
            servletStream.stream = new ByteArrayInputStream(rawData);
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            if (rawData == null) {
                rawData = IOUtils.toByteArray(this.request.getReader());
                servletStream.stream = new ByteArrayInputStream(rawData);
            }
            return servletStream;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            if (rawData == null) {
                rawData = IOUtils.toByteArray(this.request.getReader());
                servletStream.stream = new ByteArrayInputStream(rawData);
            }
            return new BufferedReader(new InputStreamReader(servletStream));
        }


        private class ResettableServletInputStream extends ServletInputStream {

            private InputStream stream;

            @Override
            public int read() throws IOException {
                return stream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        }
    }

}

你可能感兴趣的:(Spring-基础)