Spring Boot 3 进阶实战:切面编程、调度任务、邮件发送与应用监控

Spring Boot 3 进阶实战:切面编程、调度任务、邮件发送与应用监控
1. 引言Spring Boot 3 进阶功能概览主要涉及如下几个功能点调度任务在应用中提供一定的轻量级的调度能力比如方法按指定的定时规则执行或者异步执行从而完成相应的代码逻辑邮件发送邮件作为消息体系中的渠道是常用的功能应用监控实时或定期监控应用的健康状态以及各种关键的指标信息切面编程通过预编译方式和运行期动态代理实现程序中部分功能统一维护的技术可以将业务流程中的部分逻辑解耦处理提升可复用性2. 项目工程搭建与配置2.1 工程模块结构设计工程采用标准的 Maven 多模块结构核心模块如下boot-senior主模块包含启动类和核心配置boot-senior-aop切面编程相关组件boot-senior-schedule调度任务相关组件boot-senior-mail邮件发送相关组件boot-senior-actuator应用监控相关组件2.2 核心依赖管理配置!-- 基础框架依赖 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId version${spring-boot.version}/version /dependency !-- 应用监控组件 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-actuator/artifactId version${spring-boot.version}/version /dependency !-- 切面编程组件 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-aop/artifactId version${spring-boot.version}/version /dependency !-- 邮件发送组件 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-mail/artifactId version${spring-boot.version}/version /dependency这里再细致的查看一下各个功能的组件依赖体系SpringBoot只是提供了强大的集成能力2.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 RuntimeException(e); } log.info(async-job-01-end...); } Async(asyncPool) public void asyncJobPool (){ try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { throw new RuntimeException(e); } log.info(async-job-02-end...); } }1.2 线程池定义一个ThreadPoolTaskExecutor线程池对象Configuration public class PoolConfig { Bean(asyncPool) public Executor asyncPool () { ThreadPoolTaskExecutor executor new ThreadPoolTaskExecutor(); // 线程池命名前缀 executor.setThreadNamePrefix(async-pool-); // 核心线程数5 executor.setCorePoolSize(5); // 最大线程数10 executor.setMaxPoolSize(10); // 缓冲执行任务的队列50 executor.setQueueCapacity(50); // 线程的空闲时间60秒 executor.setKeepAliveSeconds(60); // 线程池对拒绝任务的处理策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 线程池关闭的时等待所有任务都完成再继续销毁其他的Bean executor.setWaitForTasksToCompleteOnShutdown(true); // 设置线程池中任务的等待时间 executor.setAwaitTerminationSeconds(300); return executor; } }1.3 输出信息从输出的日志信息中可以发现两个异步方法所使用的线程池不一样asyncJob()使用的是 Spring 默认的SimpleAsyncTaskExecutor而asyncJobPool()使用的是自定义的asyncPool线程池。通过线程池配置可以更好地控制异步任务的执行资源。2、定时任务2.1 固定频率执行Component public class FixedRateTask { private static final Logger log LoggerFactory.getLogger(FixedRateTask.class); Scheduled(fixedRate 5000) public void executeTask() { log.info(固定频率任务执行当前时间{}, LocalDateTime.now()); } }2.2 Cron 表达式执行Component public class CronTask { private static final Logger log LoggerFactory.getLogger(CronTask.class); Scheduled(cron 0 */5 * * * ?) public void executeCronTask() { log.info(Cron 表达式任务执行每5分钟执行一次当前时间{}, LocalDateTime.now()); } }五、邮件发送1、配置邮件服务spring: mail: host: smtp.example.com port: 587 username: your-emailexample.com password: your-password properties: mail: smtp: auth: true starttls: enable: true2、邮件发送服务Service public class EmailService { Autowired private JavaMailSender mailSender; public void sendSimpleEmail(String to, String subject, String text) { SimpleMailMessage message new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); mailSender.send(message); } public void sendHtmlEmail(String to, String subject, String htmlContent) throws MessagingException { MimeMessage message mailSender.createMimeMessage(); MimeMessageHelper helper new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(htmlContent, true); mailSender.send(message); } }六、应用监控1、Actuator 端点配置management: endpoints: web: exposure: include: health,info,metrics,env endpoint: health: show-details: always2、自定义健康检查Component public class CustomHealthIndicator implements HealthIndicator { Override public Health health() { boolean isHealthy checkSystemHealth(); if (isHealthy) { return Health.up() .withDetail(message, 系统运行正常) .withDetail(timestamp, System.currentTimeMillis()) .build(); } else { return Health.down() .withDetail(message, 系统出现异常) .withDetail(error, 数据库连接失败) .build(); } } private boolean checkSystemHealth() { // 实现自定义健康检查逻辑 return true; } }七、总结本文介绍了 Spring Boot 3 中四个进阶功能的用法切面编程、调度任务、邮件发送和应用监控。通过这些功能的组合使用可以构建更加健壮、可维护的企业级应用。在实际开发中建议根据具体业务需求选择合适的配置和实现方式。

最新新闻

日新闻

周新闻

月新闻