异步任务
测试如下:
进行等待三秒在进行应答
@Service
public class AsynService { public void hello(){
try {
Thread.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理数据.....");
}
}
controller类:
@Controller
public class AsynController { @Autowired
AsynService asynService; @ResponseBody
@RequestMapping("/hello")
public String hello(){
asynService.hello();
return "success";
}
}
此时会有三秒的等待响应时间!!!!
但是如果工程量大的话,这样会比较麻烦
@Service
public class AsynService { //告诉spring这是一个异步的方法
@Async
public void hello(){
try {
Thread.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.println("处理数据.....");
}
}
开启方法:
@EnableAsync
@SpringBootApplication
public class TaskApplication { public static void main(String[] args) {
SpringApplication.run(TaskApplication.class, args);
} }
执行时 会立即响应 但是打印输出会在三秒之后
定时任务
项目开发中经常需要执行一些定时任务
比如凌晨时候,分析一个前一天的日志信息
Spring为我们提供了异步执行任务调度的方式
提供了TaskExecutor、TaskScheduler接口
cron属性:
*代表全部
定时做打印操作:
@Service
public class ScheduleService { //cron:second、minute、hour、day of mounth、day of week
@Scheduled(cron ="0 * * * * MON-SAT" )
public void hello(){
System.out.println("定时处理");
} }
开启注解:
//开启定时任务
@EnableScheduling
@SpringBootApplication
public class TaskApplication {
public static void main(String[] args) {
SpringApplication.run(TaskApplication.class, args);
}
}
在任意分钟的0-10s进行打印
@Scheduled(cron = "0-10 * * * * 0-7")
public void hello(){
System.out.println("定时处理");
}
邮件任务
-邮寄发送需要引入spring-boot-starter-mail
-Springboot 自动配置MailSenderAutoConfiguration
-定义MailProperties内容,配置在application.yml中
-自动装配JavaMailSender
-测试邮件的发送
自动配置的类

@ConfigurationProperties(
prefix = "spring.mail"
)
public class MailProperties {
private static final Charset DEFAULT_CHARSET;
private String host;
private Integer port;
private String username;
private String password;
private String protocol = "smtp";
private Charset defaultEncoding;
private Map<String, String> properties;
private String jndiName;
...
}
配置文件:
spring.mail.username=@qq.com
#授权码
spring.mail.password=keoszgbsssddbaad
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true
host:
测试代码:
简单邮件
@Autowired
JavaMailSenderImpl javaMailSender; @Test
public void contextLoads() {
SimpleMailMessage msg = new SimpleMailMessage();
//邮件设置
msg.setSubject("猪头");
msg.setText("你就是猪头哦!!");
msg.setTo("xxxxxxxxx@qq.com");
msg.setFrom("12872213xx@qq.com"); javaMailSender.send(msg);
}
测试中邮件是可以成功发送的!!!
复杂的邮件测试:
@Test
public void test1() throws MessagingException {
//创建复杂邮件
MimeMessage msg = javaMailSender.createMimeMessage();
//上传文件
MimeMessageHelper helper = new MimeMessageHelper(msg,true); //邮件设置
helper.setSubject("pig"); helper.setText("<b style='color:red'>pig..... </b>",true);
helper.setTo("3212393029@qq.com");
helper.setFrom("12872213xx@qq.com"); //上传文件
helper.addAttachment("319898.jpg",new File("D:\\Tools\\319898.jpg")); javaMailSender.send(msg);
}
html的设置等都可以显示,图片的上传!!!