SpringBoot框架学习(十一)——任务

十五、SpringBoot与任务

搭建环境,暂且只选择Web模块
SpringBoot框架学习(十一)——任务
这里由于作者的8080端口被占用了,所以设置为8765端口了。

异步任务

目的:发送邮件,处理数据的时候不阻塞接下来的进程
首先在Service层建立一个我们的异步任务

@Service
public class AsynService {
    public void hello() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("等待中");
    }

}

然后在控制层,调用我们的业务

@RestController
public class AsynController {

    @Autowired
    AsynService asynService;


    @GetMapping("/hello")
    public String hello() {
        asynService.hello();
        return "success";
    }
}

然后运行,我们发现的确延迟了3秒,但是如果我们需要多线程的实现这延迟,就会很麻烦,所以在这里进行一下优化。
让Spring内部知道我们是多线程的,帮助我们内部启动一个线程池。

@Service
public class AsynService {

    //告诉Spring这是一个异步方法,这样Spring内部就会自动展开一个线程池
    @Async
    public void hello() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("等待中");
    }

}

只需要加上这一个注解。
并且在主类中开启这个注解
@EnableAsync

定时任务

项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor 、TaskScheduler 接口。

首先开始写我们的业务层代码案例

@Service
public class ScheduledService {

    /**
     * second, minute, hour, day of month, month and day of week
     * "0 * * * * MON-FRI"
     */
    @Scheduled(cron = "0 * * * * MON-FRI")
    public void hello() {
        System.out.println("Hello world");
    }
}

然后在启动类上开启@EnableScheduling注解,就可以启动我们的定时任务了
SpringBoot框架学习(十一)——任务
SpringBoot框架学习(十一)——任务
SpringBoot框架学习(十一)——任务

邮件任务

用于邮件发送。
首先导入相关的maven依赖

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

并且对于我们的properties文件进行相关配置

server.port=8765
[email protected]
spring.mail.password=xxxxx
spring.mail.host=smtp.qq.com

然后写业务层代码

@RunWith(SpringRunner.class)
@SpringBootTest
public class TaskApplicationTests {

    @Autowired
    JavaMailSender javaMailSender;
    @Test
    public void contextLoads() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //邮件设置
        simpleMailMessage.setSubject("通知");
        simpleMailMessage.setText("zz是弱智");
        simpleMailMessage.setTo("[email protected]");
        simpleMailMessage.setFrom("[email protected]");

        javaMailSender.send(simpleMailMessage);
    }

}

运行代码,发现邮件发送成功
SpringBoot框架学习(十一)——任务