springboot的任务调度

13.1 异步任务

在方法上加注解@Async

@Service
public class AsyncService {

    //告诉spring这是一个异步的方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理中");
    }
}

在main方法上加注解@EnableAsync开启异步功能

@EnableAsync
@SpringBootApplication
public class Springboot10TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot10TestApplication.class, args);
    }
}

就可以一瞬间响应,无需等待!

13.2 邮件任务

导入依赖

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

一个简单的邮件

1.先配置相关信息,先在qq邮件设置里将POP3/SMTP服务开启

spring.mail.username=971223772@qq.com
spring.mail.password=zyvegqhkctuobeif
spring.mail.host=smtp.qq.com
#开启加密验证
spring.mail.properties.mail.smtp,ssl.enable=true

2.测试

@SpringBootTest
class Springboot10TestApplicationTests {

    @Autowired(required = false)
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        SimpleMailMessage mailMessage = new SimpleMailMessage();

        mailMessage.setSubject("牛牛的Java学习之旅!");
        mailMessage.setText("加油继续努力!");
        mailMessage.setTo("971223772@qq.com");
        mailMessage.setFrom("971223772@qq.com");

        mailSender.send(mailMessage);

    }

}

一个复杂的邮件发送

@SpringBootTest
class Springboot10TestApplicationTests {

    @Autowired(required = false)
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() throws MessagingException {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组件
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
        //设置主题
        messageHelper.setSubject("牛牛的Java的学习");
        messageHelper.setText("<p style='color:red'>继续加油学习!冲鸭!</p>",true);
        //附件 绝对地址
        messageHelper.addAttachment("1.jpg",new File("C:\\Users\\liuxiang\\Desktop\\1.jpg"));
        messageHelper.setTo("971223772@qq.com");
        messageHelper.setFrom("971223772@qq.com");
        mailSender.send(mimeMessage);
    }
}

封装成工具类

//封装成工具类
    /**
     *
     * @param html
     * @param subject
     * @param text
     * @param fileName
     * @param fileUrl
     * @param ReceiveAddress
     * @param sendAddress
     * @throws MessagingException
     * @Author liuxiang
     */
    public void sendMail(Boolean html,String subject,String text,String fileName,String fileUrl,String ReceiveAddress,String sendAddress) throws MessagingException{

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组件
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,html);
        //设置主题
        messageHelper.setSubject(subject);
        messageHelper.setText(text,html);
        //附件 绝对地址
        messageHelper.addAttachment(fileName,new File(fileUrl));
        messageHelper.setTo(ReceiveAddress);
        messageHelper.setFrom(sendAddress);
        mailSender.send(mimeMessage);
    }

13.3 定时任务

  1. 在main线程开启定时功能的注解
@EnableAsync
@EnableScheduling //开始定时功能的注解
@SpringBootApplication
public class Springboot10TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot10TestApplication.class, args);
    }
}
  1. 使用 @Scheduled(cron = “0 * * * * 0-7”)注解和cron表达式
@Service
public class ScheduleService {

    //在一个特定的事件执行这个方法
    //cron表达式 任务调度
    //秒 分 时 日 月 周几
    @Scheduled(cron = "0 * * * * 0-7")
    public void hello(){
        System.out.println("hello");
    }
}

补充一个文件上传和下载的实现:

文件上传和下载

springMVC中没有装配MultipartResolver,所以默认情况下不能处理文件上传工作,如果想要使用文件上传功能,需要在上下文中配置MultipartResolver。

前端表单要求:必须将表单的method设置为POST,并将enctype设置为multipart/form-data,只有在这种情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器。

  • application/x-www=form-urlencoded:默认方式,只处理表单域中的value属性值,采用这种编码方式的表单会将表单域中的值处理成URL编码方式。
  • multipart/form-data:这种编码方式会以二进制流的方式来处理表单数据,这种编码丰富会把文件域指定文件的内容也封装到请求参数中,不会对字符编码
  • text/plain:除了把空格转换为"+"号外,其他字符不作编码处理,适用 直接通过表单发送右键
<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="file">
    <input type="submit">
  </form>

后端导入文件上传的jar包:commons-fileupload

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>

在resources目录下的springmvc-servlet.xml配置:

<!--文件上传配置-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--请求的编码格式,必须和jsp的pageEncoding属性一致,默认是ISO-8859-1-->
        <property name="defaultEncoding" value="utf-8"/>
        <!--上传文件大小上限,单位为字节(10485760=10M)-->
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>

controller层

package com.liu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
public class FileController {

    //@RequestMapping("file") 将name=file控件得到的文件封装成CommonsMultipartFile对象
    //批量上传CommonsMultipartFile则为数组即可
    @RequestMapping("/upload")
    public String fileUpLoad(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //获取文件名:file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();

        //如果文件名为空,直接回到首页
        if ("".equals(uploadFileName)){
            return "redirect:/index.jsp";
        }
        System.out.println("上传文件名:"+uploadFileName);

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload");
        //如果路径不存在,创建一个
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址:"+realPath);

        InputStream is = file.getInputStream();//文件输入流
        FileOutputStream os = new FileOutputStream(new File(realPath, uploadFileName));//输出流

        //读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len=is.read(buffer))!=-1){
            os.write(buffer,0,len);
            os.flush();
        }
        os.close();
        is.close();

        return "redirect:/index.jsp";
    }
}

方法二:

//采用file.TransferTo来保存上传的文件
    @RequestMapping("/upload2")
    public String fileUpLoad2(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload");
        //如果路径不存在,创建一个
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址:"+realPath);

        //通过CommonsMultipartFile的方法直接写文件
        file.transferTo(new File(realPath +"/" + file.getOriginalFilename()));

        return "redirect:/index.jsp";
    }

文件下载

  1. 设置response响应头
  2. 读取文件InputStream
  3. 写出文件OutputStream
  4. 执行操作
  5. 关闭流
//下载图片方法
    @RequestMapping("/downLoad")
    public String downLoads(HttpServletResponse response,HttpServletRequest request) throws IOException {
        //要下载的图片
        String path = request.getServletContext().getRealPath("/upload");
        String fileName = "基础语法.jpg";

        //1.设置response响应头
        response.reset();//设置页面不缓存,清空buffer
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");//二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
        File file = new File(path, fileName);
        //2.读取文件--输入流
        InputStream is = new FileInputStream(file);
        //3.写出文件-输出流
        OutputStream fos = response.getOutputStream();

        byte[] buffer = new byte[1024];
        int index = 0;
        while ((index = is.read(buffer))!=-1){
            fos.write(buffer,0,index);
            fos.flush();
        }

        fos.close();
        is.close();

        return null;
    }
<a href="${pageContext.request.contextPath}/downLoad">下载图片</a>