栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot的任务调度

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot的任务调度

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 邮件任务

导入依赖


    org.springframework.boot
    spring-boot-starter-test

一个简单的邮件

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("

继续加油学习!冲鸭!

",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); } }

封装成工具类

 //封装成工具类
    
    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:除了把空格转换为"+"号外,其他字符不作编码处理,适用 直接通过表单发送右键

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


commons-fileupload
commons-fileupload
1.3.3


javax.servlet
javax.servlet-api
4.0.1

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


    
        
        
        
        
        
    

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;
    }
 下载图片
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1021075.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号