SpringBoot使用AOP统一处理请求日志

这里就提到了我们Spring当中的AOP,也就是面向切面编程,今天我们使用AOP去对我们的所有请求进行一个统一处理。首先在pom.xml中引入我们需要的aop的jar包

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

然后我们新建一个Aspect去对我们的所有Controller进行一个日志拦截。在SPringBoot中我们使用AOP也是很简单的,只需要在类上加上一个@Aspect的注解就好了,然后通过@Component注解到我们的Spring容器中去。

我们新建一个包com.majiaxueyuan.log专门用来放我们的日志记录,代码如下:

@Aspect
@Component
@Slf4j
public class MjxyLogAspect {
 //第一个 * 号表示任意返回类型,第二个 * 号表示Person的所有方法
@Pointcut("execution(public * com.majiaxueyuan.controller..*.*(..))")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
log.info("URL : " + request.getRequestURL().toString());
log.info("HTTP_METHOD : " + request.getMethod());
log.info("IP : " + request.getRemoteAddr());
Enumeration<String> enu = request.getParameterNames();
while (enu.hasMoreElements()) {
String name = (String) enu.nextElement();
log.info("name:{},value:{}", name, request.getParameter(name));
}
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
log.info("RESPONSE : " + ret);
}
}

然后我们通过浏览器随便请求一次,可以看到控制台输出,这里我们就可以在实际生产环境中存储日志。

SpringBoot定时任务@Scheduled

在service中新建一个类ScheduledTest,代码如下:

@Component
public class ScheduledTest {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

@Scheduled(fixedRate = 2000)
public void scheduled() {
System.out.println("码家学院提示你==》现在时间:" + dateFormat.format(new Date()));
}
}

另外我们需要在主函数启动类上开启定时器

@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

SpringBoot异步调用Async

这个和定时器差不多,启动加上@EnableAsync ,只需要在我们需要异步的方法上面加上@Async注解

异步就是在主线程中部分代码执行另一个线程,而另一个线程不影响主线程的执行。

AsyncTest.java

@Component
public class AsyncTest{
 	@Async
 	public void asyncOut(){
		sout(Thread.currentThread().geetId());
	}
}

启动类中

@SpringBootApplication
@EnableAsync
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
@RequestMapping("/login")
public String login(){
sout(Thread.currentThread().getId());
asyncTest.asyncOut();
return "loginPage"
}

运行的结果发现两个id是不同的,说明成功了。

自定义参数

在配置文件中我们可以去在配置文件中自定义一些参数,比如:

name=majiaxueyuan

我们在代码中获取到我们的这个配置文件

@Value("${name}")
private String name;
@ResponseBody
@RequestMapping("/getValue")
public String getValue() {
return name;
}

SpringBoot学习笔记(七):SpringBoot使用AOP统一处理请求日志、SpringBoot定时任务@Scheduled、SpringBoot异步调用Async、自定义参数的更多相关文章

  1. Spring Boot 表单验证、AOP统一处理请求日志、单元测试

    一.使用@Valid表单验证 于实体类中添加@Min等注解 @Entity public class Girl { @Id @GeneratedValue private Integer id; pr ...

  2. Springboot中AOP统一处理请求日志

    完善上面的代码: 现在把输出信息由先前的system.out.println()方式改为由日志输出(日志输出的信息更全面) 现在在日志中输出http请求的内容 在日志中获取方法返回的内容

  3. SpringBoot学习笔记

    SpringBoot个人感觉比SpringMVC还要好用的一个框架,很多注解配置可以非常灵活的在代码中运用起来: springBoot学习笔记: .一.aop: 新建一个类HttpAspect,类上添 ...

  4. springboot 学习笔记(二)

    springboot 学习笔记(二) 快速创建一个springboot工程,并引入所需要的依赖 1.利用Spring initializr 来创建一个springboot项目,登陆http://sta ...

  5. SpringBoot学习笔记(7):Druid使用心得

    SpringBoot学习笔记(7):Druid使用心得 快速开始 添加依赖 <dependency> <groupId>com.alibaba</groupId> ...

  6. SpringBoot学习笔记(8):事物处理

    SpringBoot学习笔记(8):事物处理 快速入门 在传统的JDBC事务代码开发过程中,业务代码只有一部分,大部分都是与JDBC有关的功能代码,比如数据库的获取与关闭以及事务的提交与回滚.大量的t ...

  7. springboot学习笔记:9.springboot+mybatis+通用mapper+多数据源

    本文承接上一篇文章:springboot学习笔记:8. springboot+druid+mysql+mybatis+通用mapper+pagehelper+mybatis-generator+fre ...

  8. Springboot学习笔记(六)-配置化注入

    前言 前面写过一个Springboot学习笔记(一)-线程池的简化及使用,发现有个缺陷,打个比方,我这个线程池写在一个公用服务中,各项参数都定死了,现在有两个服务要调用它,一个服务的线程数通常很多,而 ...

  9. SpringBoot学习笔记(14):使用SpringBootAdmin管理监控你的应用

    SpringBoot学习笔记(14):使用SpringBootAdmin管理监控你的应用 Spring Boot Admin是一个管理和监控Spring Boot应用程序的应用程序.本文参考文档: 官 ...

随机推荐

  1. tarjan模板 强联通分量+割点+割边

    // https://www.cnblogs.com/stxy-ferryman/p/7779347.html ; struct EDGE { int to, nt; }e[N*N]; int hea ...

  2. 2018湘潭大学程序设计竞赛【H】

    题目链接:https://www.nowcoder.com/acm/contest/105/H 题意:两个操作,一个在[l,r]区间放颜色为c的球,一个统计在[l,r]里有多少不同颜色的球. 题解:哎 ...

  3. OC中Nil nil NULL 和 [NSNULL null]的区别

    关于这个问题看过两三次了,但是每次过两个月脑袋里又会不清晰,索性记录一下加深一下印象. 一.nil 当一个对象置为nil时,这个对象的内存地址就会被系统收回.置空之后是不能进行retain,copy等 ...

  4. PL SQL 12.0.7的安装及注册码,汉化包,连接Oracle远程数据库,中文乱码问题处理

    首先,在官网下载PL SQL 的对应版本,本机是64位的就下载64位的,网址:https://www.allroundautomations.com/downloads.html#PLS 点击应用程序 ...

  5. ResultSetMetaData中getColumnLabel和getColumnName的区别

    利用jdbc连接数据库查询时,通常返回的结果就是每行数据的键值对集合.这时我们需要知道查询出来的数据有哪些字段.根据ResultSet结果集得到的ResultSetMetaData就可以获取到每个字段 ...

  6. Erlang学习记录:语法和特性

    特性 大下排序:number < atom < reference < fun < port < pid < tuple < list < bit st ...

  7. 廖雪峰Java16函数式编程-2Stream-5filter

    1.filter简介 Stream.filter()是一个转换方法,把一个Stream转换为另一个Stream. 所谓filter操作,就是对一个Stream的所有元素进行测试,不满足条件的元素就被过 ...

  8. 「STL」bitset正传

    前言 之前一些需要转二进制来解决的题目我看到很多大佬用了bitset. 然而我并不会这东西.看上去很高级的样子…… 改题改累了来学习一下233. 正文 一.bitset的构造 bitset有三种构造方 ...

  9. 跨域问题The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by t

    withCredentials 属性 上面说到,CORS请求默认不发送Cookie和HTTP认证信息.如果要把Cookie发到服务器,一方面要服务器同意,指定Access-Control-Allow- ...

  10. php开发面试题---面试常用英语(你能介绍你自己吗?)

    php开发面试题---面试常用英语(你能介绍你自己吗?) 一.总结 一句话总结: Could you please describe yourself? 1.为什么觉得自己适合这份工作? Why do ...