关于程序员:SpringBoot中的异步任务邮件以及定时任务

9次阅读

共计 3130 个字符,预计需要花费 8 分钟才能阅读完成。

异步工作

背景

在咱们的业务解决中,比方解决实现须要 3s 能力实现,然而咱们须要如果要让用户等 3s,则体验十分差,所以咱们采纳异步的形式去解决,能够通过线程池来解决,然而还要写线程,而 springboot 中曾经默认提供了这种能力,咱们只有开启即可应用。

具体应用

  • 创立我的项目

咱们只有创立一个根本的 springboot 我的项目,而后只有增加 web 的依赖即可。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • 编写场景模仿下面背景

service 层:

@Service
public class AsyncService {public void sync(){
        try {TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {e.printStackTrace();
        }

        System.out.println("办法中在执行中");
    }

    public void async(){
        try {TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {e.printStackTrace();
        }

        System.out.println("办法中在执行中");
    }
}

controller 层

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;


    @GetMapping("/sync")
    public String sync(){asyncService.sync();

        return "解决实现";
    }

    @GetMapping("/async")
    public String async(){asyncService.async();
        
        return "解决实现";
    }

}
  • 启动我的项目,测试

申请 localhost:8080/sync,发现会转圈期待 3s 后才有返回值:

  • 问题解决

采纳异步的形式来解决这个问题。

首先在启动类上关上异步:@EnableAsync,而后再调用的办法上增加注解 @Async

# 启动类
 @SpringBootApplication
@EnableAsync
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);
    }
}
# 办法
    @Async
    public void async(){
        try {TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {e.printStackTrace();
        }

        System.out.println("办法中在执行中");
    }

而后再次申请 ocalhost:8080/async,发现咱们的办法立马就返回了。这样就是实现了异步工作。

邮件工作

背景

通过 springboot 提供的 mail-starter 来实现邮件工作。

具体应用

  • 增加依赖
 <!--mail-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  • 配置文件

spring.mail.username=xxxx@qq.com
spring.mail.password= 你的 qq 受权码
spring.mail.host=smtp.qq.com
# qq 须要配置 ssl
spring.mail.properties.mail.smtp.ssl.enable=true

获取受权码:在 QQ 邮箱中的设置 -> 账户 -> 开启 pop3 和 smtp 服务.

  • Spring 单元测试
@Autowired
JavaMailSenderImpl mailSender;

@Test
public void contextLoads() {
   // 邮件设置 1:一个简略的邮件
   SimpleMailMessage message = new SimpleMailMessage();
   message.setSubject("告诉 - 今天来下班");
   message.setText("今晚 7:30 散会");

   message.setTo("xxx@qq.com");
   message.setFrom("xxx@qq.com");
   mailSender.send(message);
}

@Test
public void contextLoads2() throws MessagingException {
   // 邮件设置 2:一个简单的邮件
   MimeMessage mimeMessage = mailSender.createMimeMessage();
   MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

   helper.setSubject("告诉 - 今天吃饭");
   helper.setText("<b style='color:red'> 明天 7:30 来散会 </b>",true);

   // 发送附件
   helper.addAttachment("1.jpg",new File(""));
   helper.addAttachment("2.jpg",new File(""));

   helper.setTo("xxx@qq.com");
   helper.setFrom("xxx@qq.com");

   mailSender.send(mimeMessage);

定时工作

背景

在指定的工夫或者场景下执行某些代码。

相关联的类和注解

TaskScheduler  : 任务调度者
TaskExecutor:工作执行者
@EnableScheduling  : 开启定时性能的注解
@schedule:什么时候执行 

具体应用

只有导入了 springboot 的 web 依赖,就默认给咱们导入了这个性能,不须要咱们再去导入。

对于 cron 表达式的能够参考我的另一篇文章:spring 中 @schedule 注解的应用

  • 在启动类上增加注解 @EnableScheduling
@SpringBootApplication
@EnableAsync
@EnableScheduling
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);
    }
}
  • service 层编写办法
@Service
public class ScheduleService {public void testSchedule(){System.out.println("工作被执行了");
    }
}
  • 增加注解 @Scheduled

其中的 cron 表达式能够参考我的另一篇博客:spring 中 @schedule 注解的应用,也就是固定的工夫周期去执行

@Service
public class ScheduleService {


    /**
     * 每隔 10s 执行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void testSchedule(){System.out.println(LocalDateTime.now()+"工作被执行了");
    }
}
  • 后果

每隔 10s 执行一次,验证了准确性。

正文完
 0