springboot使用注解配置要监听的接口并记录日志

1. 添加依赖

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-aop</artifactId>

</dependency>


2. 编写自定义注解类

package com.atguigu.springcloud.interfacePackage;

import java.lang.annotation.*;

@Target({ ElementType.METHOD, ElementType.TYPE })

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface MyLog {

    String value();

}

3. 编写注解类切面

package com.atguigu.springcloud.aop;

import com.atguigu.springcloud.interfacePackage.MyLog;
import com.atguigu.springcloud.log.InterFaceLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;


@Aspect
@Component
public class WebLogAspect {
    ThreadLocal<Long> startTime = new ThreadLocal<>();
    ThreadLocal<InterFaceLog> log = new ThreadLocal<>();
    InterFaceLog interfaceLog =  new InterFaceLog();

    @Pointcut("@annotation(com.atguigu.springcloud.interfacePackage.MyLog)")
    public void annotationPointCut(){}

    @Before("annotationPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求,记录请求内容
        startTime.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String remoteAddr = request.getRemoteAddr();
        String class_method = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        String param = Arrays.toString(joinPoint.getArgs());
        log.set(interfaceLog);


        MethodSignature sign =  (MethodSignature)joinPoint.getSignature();
        Method method2 = sign.getMethod();
        MyLog annotation = method2.getAnnotation(MyLog.class);
        System.out.print("打印:"+annotation.value()+" 前置日志");
    }

    @AfterReturning(returning = "ret", pointcut = "annotationPointCut()")
    public void doAfterReturning(Object ret) throws Throwable {
        String result = ret.toString();
        InterFaceLog logAfter =  log.get();
        Long time = System.currentTimeMillis() - startTime.get();
        System.out.println(logAfter);
    }
}

4、在启动类中添加对aspect的支持

@EnableAspectJAutoProxy//没有用到

5、在controller层中使用注解

package com.atguigu.springcloud.controller;

import java.util.List;

import com.atguigu.springcloud.interfacePackage.MyLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.atguigu.springcloud.entities.Dept;
import com.atguigu.springcloud.service.DeptService;

@RestController
public class DeptController
{
	@Autowired
	private DeptService service;

	@Autowired
	private DiscoveryClient client;

	@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
	public boolean add(@RequestBody Dept dept)
	{
		return service.add(dept);
	}

	@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
	public Dept get(@PathVariable("id") Long id)
	{
		return service.get(id);
	}
	@MyLog("测试")
	@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
	public List<Dept> list()
	{
		return service.list();
	}
	@RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
	public Object discovery()
	{
		/**获取eureka里面的服务*/
		List<String> list = client.getServices();
		System.out.println("**********" + list);

		List<ServiceInstance> srvList = client.getInstances("MICROSERVICECLOUD-DEPT");
		for (ServiceInstance element : srvList) {
			System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
					+ element.getUri());
		}
		return this.client;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_31896193/article/details/84523695