标签:切面.调度.邮件.监控;
一、简介
在上篇《SpringBoot3基础》中已经完成入门案例的开发和测试,在这篇内容中再来看看进阶功能的用法;
主要涉及如下几个功能点:
调度任务:在应用中提供一定的轻量级的调度能力,比如方法按指定的定时规则执行,或者异步执行,从而完成相应的代码逻辑;
邮件发送:邮件作为消息体系中的渠道,是常用的功能;
应用监控:实时或定期监控应用的健康状态,以及各种关键的指标信息;
切面编程:通过预编译方式和运行期动态代理实现程序中部分功能统一维护的技术,可以将业务流程中的部分逻辑解耦处理,提升可复用性;
二、工程搭建
1、工程结构
2、依赖管理
<!-- 基础框架依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<!-- 应用监控组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<!-- 切面编程组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<!-- 邮件发送组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>${spring-boot.version}</version>
</dependency>
这里再细致的查看一下各个功能的组件依赖体系,SpringBoot
只是提供了强大的集成能力;
3、启动类
注意在启动类中使用注解开启了异步EnableAsync
和调度EnableScheduling
的能力;
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
三、切面编程
1、定义注解
定义一个方法级的注解;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface DefAop {
/**
* 模块描述
*/
String modelDesc();
/**
* 其他信息
*/
String otherInfo();
}
2、注解切面
在切面中使用Around
环绕通知类型,会拦截到DefAop
注解标记的方法,然后解析获取各种信息,进而嵌入自定义的流程逻辑;
@Component
@Aspect
public class LogicAop {
private static final Logger logger = LoggerFactory.getLogger(LogicAop.class) ;
/**
* 切入点
*/
@Pointcut("@annotation(com.boot.senior.aop.DefAop)")
public void defAopPointCut() {
}
/**
* 环绕切入
*/
@Around("defAopPointCut()")
public Object around (ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Object result = null ;
try{
// 执行方法
result = proceedingJoinPoint.proceed();
} catch (Exception e){
e.printStackTrace();
} finally {
// 处理逻辑
buildLogicAop(proceedingJoinPoint) ;
}
return result ;
}
/**
* 构建处理逻辑
*/
private void buildLogicAop (ProceedingJoinPoint point){
// 获取方法
MethodSignature signature = (MethodSignature) point.getSignature();
Method reqMethod = signature.getMethod();
// 获取注解
DefAop defAop = reqMethod.getAnnotation(DefAop.class);
String modelDesc = defAop.modelDesc() ;
String otherInfo = defAop.otherInfo();
logger.info("DefAop-modelDesc:{}",modelDesc);
logger.info("DefAop-otherInfo:{}",otherInfo);
}
}
四、调度任务
1、异步处理
1.1 方法定义
通过Async
注解标识两个方法,方法在执行时会休眠10秒,其中一个注解指定异步执行使用asyncPool
线程池;
@Service
public class AsyncService {
private static final Logger log = LoggerFactory.getLogger(AsyncService.class);
@Async
public void asyncJob (){
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
throw new R