SpringBoot3进阶用法

梦里梦外; 2024-03-23 21:46 103阅读 0赞

一、简介

在这篇内容中再来看看进阶功能的用法;

主要涉及如下几个功能点:

调度任务:在应用中提供一定的轻量级的调度能力,比如方法按指定的定时规则执行,或者异步执行,从而完成相应的代码逻辑;

邮件发送:邮件作为消息体系中的渠道,是常用的功能;

应用监控:实时或定期监控应用的健康状态,以及各种关键的指标信息;

切面编程:通过预编译方式和运行期动态代理实现程序中部分功能统一维护的技术,可以将业务流程中的部分逻辑解耦处理,提升可复用性;

二、工程搭建

1、工程结构

8b961c4d8826371d68919f1815d1fd5a.png

2、依赖管理

  1. <!-- 基础框架依赖 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. <version>${spring-boot.version}</version>
  6. </dependency>
  7. <!-- 应用监控组件 -->
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-actuator</artifactId>
  11. <version>${spring-boot.version}</version>
  12. </dependency>
  13. <!-- 切面编程组件 -->
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-aop</artifactId>
  17. <version>${spring-boot.version}</version>
  18. </dependency>
  19. <!-- 邮件发送组件 -->
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-mail</artifactId>
  23. <version>${spring-boot.version}</version>
  24. </dependency>

这里再细致的查看一下各个功能的组件依赖体系,SpringBoot只是提供了强大的集成能力;

a8ed127a09e3d50ddedab4ca75748568.png

3、启动类

注意在启动类中使用注解开启了异步EnableAsync和调度EnableScheduling的能力;

  1. @EnableAsync
  2. @EnableScheduling
  3. @SpringBootApplication
  4. public class Application {
  5. public static void main(String[] args) {
  6. SpringApplication.run(Application.class, args);
  7. }
  8. }

三、切面编程

1、定义注解

定义一个方法级的注解;

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.METHOD)
  3. @Documented
  4. public @interface DefAop {
  5. /**
  6. * 模块描述
  7. */
  8. String modelDesc();
  9. /**
  10. * 其他信息
  11. */
  12. String otherInfo();
  13. }

2、注解切面

在切面中使用Around环绕通知类型,会拦截到DefAop注解标记的方法,然后解析获取各种信息,进而嵌入自定义的流程逻辑;

  1. @Component
  2. @Aspect
  3. public class LogicAop {
  4. private static final Logger logger = LoggerFactory.getLogger(LogicAop.class) ;
  5. /**
  6. * 切入点
  7. */
  8. @Pointcut("@annotation(com.boot.senior.aop.DefAop)")
  9. public void defAopPointCut() {
  10. }
  11. /**
  12. * 环绕切入
  13. */
  14. @Around("defAopPointCut()")
  15. public Object around (ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
  16. Object result = null ;
  17. try{
  18. // 执行方法
  19. result = proceedingJoinPoint.proceed();
  20. } catch (Exception e){
  21. e.printStackTrace();
  22. } finally {
  23. // 处理逻辑
  24. buildLogicAop(proceedingJoinPoint) ;
  25. }
  26. return result ;
  27. }
  28. /**
  29. * 构建处理逻辑
  30. */
  31. private void buildLogicAop (ProceedingJoinPoint point){
  32. // 获取方法
  33. MethodSignature signature = (MethodSignature) point.getSignature();
  34. Method reqMethod = signature.getMethod();
  35. // 获取注解
  36. DefAop defAop = reqMethod.getAnnotation(DefAop.class);
  37. String modelDesc = defAop.modelDesc() ;
  38. String otherInfo = defAop.otherInfo();
  39. logger.info("DefAop-modelDesc:{}",modelDesc);
  40. logger.info("DefAop-otherInfo:{}",otherInfo);
  41. }
  42. }

四、调度任务

1、异步处理

1.1 方法定义

通过Async注解标识两个方法,方法在执行时会休眠10秒,其中一个注解指定异步执行使用asyncPool线程池;

  1. @Service
  2. public class AsyncService {
  3. private static final Logger log = LoggerFactory.getLogger(AsyncService.class);
  4. @Async
  5. public void asyncJob (){
  6. try {
  7. TimeUnit.SECONDS.sleep(10);
  8. } catch (InterruptedException e) {
  9. throw new RuntimeException(e);
  10. }
  11. log.info("async-job-01-end...");
  12. }
  13. @Async("asyncPool")
  14. public void asyncJobPool (){
  15. try {
  16. TimeUnit.SECONDS.sleep(10);
  17. } catch (InterruptedException e) {
  18. throw new RuntimeException(e);
  19. }
  20. log.info("async-job-02-end...");
  21. }
  22. }

1.2 线程池

定义一个ThreadPoolTaskExecutor线程池对象;

  1. @Configuration
  2. public class PoolConfig {
  3. @Bean("asyncPool")
  4. public Executor asyncPool () {
  5. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  6. // 线程池命名前缀
  7. executor.setThreadNamePrefix("async-pool-");
  8. // 核心线程数5
  9. executor.setCorePoolSize(5);
  10. // 最大线程数10
  11. executor.setMaxPoolSize(10);
  12. // 缓冲执行任务的队列50
  13. executor.setQueueCapacity(50);
  14. // 线程的空闲时间60秒
  15. executor.setKeepAliveSeconds(60);
  16. // 线程池对拒绝任务的处理策略
  17. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  18. // 线程池关闭的时等待所有任务都完成再继续销毁其他的Bean
  19. executor.setWaitForTasksToCompleteOnShutdown(true);
  20. // 设置线程池中任务的等待时间
  21. executor.setAwaitTerminationSeconds(300);
  22. return executor;
  23. }
  24. }

1.3 输出信息

从输出的日志信息中可以发现,两个异步方法所使用的线程池不一样,asyncJob采用默认的cTaskExecutor线程池,asyncJobPool方法采用的是async-pool线程池;

  1. [schedule-pool-1] c.boot.senior.schedule.ScheduleService : async-job-02-end...
  2. [cTaskExecutor-1] c.boot.senior.schedule.ScheduleService : async-job-01-end...

2、调度任务

2.1 调度配置

通过实现SchedulingConfigurer接口,来修改调度任务的配置,这里重新定义任务执行的线程池;

  1. @Configuration
  2. public class ScheduleConfig implements SchedulingConfigurer {
  3. @Override
  4. public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
  5. scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
  6. }
  7. }

2.2 调度方法

通过Scheduled注解来标记方法,基于定时器的规则设定,来统一管理方法的执行时间;

  1. @Component
  2. public class ScheduleJob {
  3. private static final Logger log = LoggerFactory.getLogger(ScheduleJob.class);
  4. private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
  5. /**
  6. * 上一次开始执行时间点之后10秒再执行
  7. */
  8. @Scheduled(fixedRate = 10000)
  9. private void timerJob1(){
  10. log.info("timer-job-1:{}",format.format(new Date()));
  11. }
  12. /**
  13. * 上一次执行完毕时间点之后10秒再执行
  14. */
  15. @Scheduled(fixedDelay = 10000)
  16. private void timerJob2(){
  17. log.info("timer-job-2:{}",format.format(new Date()));
  18. }
  19. /**
  20. * Cron表达式:每30秒执行一次
  21. */
  22. @Scheduled(cron = "0/30 * * * * ?")
  23. private void timerJob3(){
  24. log.info("timer-job-3:{}",format.format(new Date()));
  25. }
  26. }

五、邮件发送

1、邮件配置

采用QQ邮箱来模拟邮件的发送方,需要先开启smtp邮件传输协议,在QQ邮箱的设置/账户路径下,并且获取相应的授权码,在项目的配置中使用;

e7430e3ea380a1944629c323d4271d7f.png

  1. spring:
  2. application:
  3. name: boot-senior
  4. # 邮件配置
  5. mail:
  6. host: smtp.qq.com
  7. port: 465
  8. protocol: smtps
  9. username: 邮箱账号
  10. password: 邮箱授权码
  11. properties:
  12. mail.smtp.ssl.enable: true

2、方法封装

定义一个简单的邮件发送方法,并且可以添加附件,是常用的功能之一;另外也可以通过Html静态页渲染,再转换为邮件内容的方式;

  1. @Service
  2. public class SendMailService {
  3. @Value("${spring.mail.username}")
  4. private String userName ;
  5. @Resource
  6. private JavaMailSender sender;
  7. /**
  8. * 带附件的邮件发送方法
  9. * @param toUsers 接收人
  10. * @param subject 主题
  11. * @param content 内容
  12. * @param attachPath 附件地址
  13. * @return java.lang.String
  14. * @since 2023-07-10 17:03
  15. */
  16. public String sendMail (String[] toUsers,String subject,
  17. String content,String attachPath) throws Exception {
  18. // MIME邮件类
  19. MimeMessage mimeMessage = sender.createMimeMessage();
  20. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  21. // 邮件发送方From和接收方To
  22. helper.setFrom(userName);
  23. helper.setTo(toUsers);
  24. // 邮件主题和内容
  25. helper.setSubject(subject);
  26. helper.setText(content);
  27. // 邮件中的附件
  28. File attachFile = ResourceUtils.getFile(attachPath);
  29. helper.addAttachment(attachFile.getName(), attachFile);
  30. // 执行邮件发送命令
  31. sender.send(mimeMessage);
  32. return "send...mail...sus" ;
  33. }
  34. }

测试结果

a0421addb7b97d929e8dda3d0107a770.png

六、应用监控

1、监控配置

springbootactuator组件中,可以通过提供的Rest接口,来获取应用的监控信息;

  1. # 应用监控配置
  2. management:
  3. endpoints:
  4. web:
  5. exposure:
  6. # 打开所有的监控点
  7. include: "*"
  8. base-path: /monitor
  9. endpoint:
  10. health:
  11. enabled: true
  12. show-details: always
  13. beans:
  14. enabled: true
  15. shutdown:
  16. enabled: true

2、相关接口

2.1 Get类型接口:主机:端口/monitor/health,查看应用的健康信息,三个核心指标:status状态,diskSpace磁盘空间,ping检查;

  1. {
  2. /* 状态值 */
  3. "status": "UP",
  4. "components": {
  5. /* 磁盘空间 */
  6. "diskSpace": {
  7. "status": "UP",
  8. "details": {
  9. "total": 250685575168,
  10. "free": 112149811200,
  11. "threshold": 10485760,
  12. "path": "Path/butte-spring-parent/.",
  13. "exists": true
  14. }
  15. },
  16. /* Ping检查 */
  17. "ping": {
  18. "status": "UP"
  19. }
  20. }
  21. }

2.2 Get类型接口:主机:端口/monitor/beans,查看bean列表;

  1. {
  2. "contexts": {
  3. "boot-senior": {
  4. "beans": {
  5. "asyncPool": {
  6. "scope": "singleton",
  7. "type": "org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor",
  8. "resource": "class path resource [com/boot/senior/schedule/PoolConfig.class]"
  9. },
  10. "asyncService": {
  11. "scope": "singleton",
  12. "type": "com.boot.senior.schedule.AsyncService$$SpringCGLIB$$0"
  13. }
  14. }
  15. }
  16. }
  17. }

2.3 Post类型接口:主机:端口/monitor/shutdown,关闭应用程序;

  1. {
  2. "message": "Shutting down, bye..."
  3. }

七、参考源码

  1. 文档仓库:
  2. https://gitee.com/cicadasmile/butte-java-note
  3. 源码仓库:
  4. https://gitee.com/cicadasmile/butte-spring-parent

发表评论

表情:
评论列表 (有 0 条评论,103人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot3

    一、简介 在这篇内容中再来看看进阶功能的用法; 主要涉及如下几个功能点: 调度任务:在应用中提供一定的轻量级的调度能力,比如方法按指定的定时规则执行,或者异步执行,从