SpringCloud interceptor use (Interceptors interceptor use)

Posted by ternto333 on Sun, 08 Mar 2020 17:31:26 +0100

The SpringCloud backend intercepts front-end requests, which are logging, using SpringAOP, which is face-to-face.

First, intercept the request address (ip), using the Handler Interceptor Adapter, which intercepts the request address, so it is appropriate to do some validation and preprocessing for the request address. For example, below, I use it to count the response time for requests to access this address.

    RequestLog

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.time.Instant;

/*
    HandlerInterceptoer The request address is intercepted, so it is appropriate to do some validation, preprocessing, etc. for the request address.
    For example, you need to count the response time for requests to this address
*/
/*  Filter It is specified by the Servlet specification, is not part of the spring framework, and is also used for request interception.
    However, it is suitable for coarser-grained interception, doing some coding, logging, etc. before and after the request.
*/

public class RequestLog extends HandlerInterceptorAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(RequestLog.class);

    /**
     * Pre-check, before method execution
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String ip = request.getRemoteAddr();
        Instant startTime = Instant.now();
        request.setAttribute("logrequestStartTime", startTime);
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // Get user token
        Method method = handlerMethod.getMethod();
        LOGGER.info("user:"+ip+",Access Target:"+method.getDeclaringClass().getName() + "." + method.getName());
        return true;
    }

    /**
     *  Method Execution in Progress
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    // controller processing complete
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Instant startTime = (Instant) request.getAttribute("logrequestStartTime");

        Instant endTime = Instant.now();
        long executeTime = endTime.toEpochMilli()- startTime.toEpochMilli();

        // log it
        if (executeTime > 1000) {
            LOGGER.info("[" + method.getDeclaringClass().getName() + "." + method.getName() + "] Time-consuming execution : "
                    + executeTime + "ms");
        } else {
            LOGGER.info("[" + method.getDeclaringClass().getSimpleName() + "." + method.getName() + "] Time-consuming execution : "
                    + executeTime + "ms");
        }

    }
}

Then, face-to-face interception is performed to log requests

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.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by pd on 17/12/07.
 */
//Describe the tangent class
@Aspect     //The @Aspect comment tells spring that this is an AOP class, an AOP facet
@Configuration  //Can be understood as <beans>tags in xml when using Spring, and @beans in classes can be understood as <beans>tags in xml when using Spring
public class LogRecordAspect {
private static final Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);

    // Annotate an entry method with @Pointcut
    //The @Pointcut comment declares that this is a facet that needs to be intercepted, that is, the aop is activated when any controller method is called
    @Pointcut("execution(* com.pengda.controller.*Controller.*(..))")   //Two... represent all subdirectories, two in the last bracket... represent all parameters
    public void excudeService() {
    }

    //The @Around comment wraps around execution, which executes logic before and after the call
    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();


        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        try{
            Object[] args =pjp.getArgs();
            for(int i=0;i<args.length;i++){
                if(args[i] instanceof RequestInfo<?>){
                    RequestInfo<?> r= (RequestInfo<?>) args[i];
                    logger.info("Request Start, Individual parameters, url: {}, method: {}, uri: {}, params: {}", url, method, uri, r.toString());
                }else{
                    logger.info("Request Start, Individual parameters, url: {}, method: {}, uri: {}, params: {}", url, method, uri,args[i]);
                }
            }
        }catch (Exception e){
            logger.info("Request Start, Individual parameters, url: {}, method: {}, uri: {}, params: {}", url, method, uri,queryString);
        }
        // The value of result is the return value of the intercepted method
        Object result = pjp.proceed();
        //logger.info("end of request, return value of controller is" + result.toString()));
        //logger.info("end of request, controller return value is" + result);
        return result;
    }
}

Topics: Spring Java xml