Springboot做一个定时任务(客户端和服务端)

目标效果图效果图:


客户端向服务端定时任务发送文件

最近在学习SpringBoot项目,项目模块中有用到一些,做一个定时任务调度的功能,使用restful来简单实现一下。

实现步骤

选择Create NewProject 创建一个新工程

选择Spring Initializr

springboot项目

创建一个工程,工程下面可以分模块子模块构建依赖maven构建的生态

创建工程名

这里可以添加许多依赖模块包,提供为开发者更大的简便,不用的自己配置复杂的配置文件,用着就是爽

选择添加的模块
创建模块工程名

工程创建成功后将配置pom.xml文件,具体配置如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ernestfei</groupId>
    <artifactId>spring-ernestfei-timertask</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-ernestfei-timertask</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

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

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient-cache -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient-cache</artifactId>
            <version>4.5.3</version>
        </dependency>
        <!--httpclinet请求所需包  https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.3</version>
        </dependency>
        <!--springboot web启动包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--springboot读取配置文件类-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson json工具类 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.41</version>
        </dependency>
        <!--操作文件工具类-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- 可命令行独立编译maven项目下的class文件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <proc>none</proc>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

工程目录结构如下


工程目录结构

下面我们配置一下定时任务
启动类中假如 @EnableScheduling 注解来开启任务调度

@SpringBootApplication
@EnableScheduling
public class SpringErnestfeiTimertaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringErnestfeiTimertaskApplication.class, args);
        System.out.println("=======================Springboot实现定时任务客户端demo=========================");
    }
}

调度方法如下

@Component
public class TimerTasks {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    @Resource
    private UrlConfig config;
    /**
     * 定时任务上传文件到服务器
     * */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void reportCurrentTime() {
        Date date = new Date();
        File uploadFile = new File(config.getGetFileDir()+"\\1.txt");
        FileUploadClient.uploadPassFile(config.getServerUrl(),uploadFile);
        System.out.println("{客户端定时任务开启每一分钟发送一次}===>>>"+dateFormat.format(date));
    }
}

使用HttpClinet实现客户端调度,具体如下

    /**
     * 上传文件
     *  serverUrl 上传服务器地址
     *  file 上传的文件
     *
     */
    public static void uploadFile(String serverUrl,File file0) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(serverUrl);

            FileBody file = new FileBody(file0);
            StringBody token = new StringBody("1234567", ContentType.create("text/plain", Consts.UTF_8));
            StringBody content = new StringBody(">>>{来自于客户端传来的文件}<<<", ContentType.create("text/plain", Consts.UTF_8));
            MultipartEntityBuilder builder =MultipartEntityBuilder.create();

            HttpEntity reqEntity = builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("file", file)
                    .addPart("token", token)
                    .addPart("content",content)
                    .setCharset(CharsetUtils.get("UTF-8")).build();

            httppost.setEntity(reqEntity);
            long startTime=System.currentTimeMillis();
            System.out.println("====开始执行====" + startTime);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity resEntity = response.getEntity();
                if(resEntity!=null){
                    System.out.println("==resEntity=="+resEntity.getContent());
                    System.out.println("====中文乱码检测====");
                    System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
                }
                EntityUtils.consume(resEntity);
                long endTime=System.currentTimeMillis();
                System.out.println("====结束执行====" + endTime);
                System.out.println("====执行时间====" + (endTime - startTime));
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            System.out.println("====服务器端无法连接异常====");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("====服务器端无法连接异常====");
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

服务端Contoller层处理客户端调用处理

@RestController
public class FileUploadController {
    @Resource
    private UrlConfig config;
    @PostMapping("uploadFile")
    public Object uploadFile(@RequestParam(value = "file")MultipartFile file,@RequestParam(value = "token")String token,@RequestParam(value = "content",required = false)String content){
        Map<String,Object> resMap = new HashMap<>(8);
        System.out.println("{服务端接受内容}===>>>"+content);
        if(token.equals(config.getToken())){
            System.out.println("{上传的文件名为}===>>>"+file.getOriginalFilename());
            resMap.put("status",200);
            resMap.put("message","服务端返回=上传成功,返回文件"+file.getOriginalFilename());
        }else{
            resMap.put("status",400);
            resMap.put("message","服务端返回=上传失败,TOKEN校验失败!");
        }
        return JSON.toJSONString(resMap);
    }
}

读取配置文件中的参数可以使用@ConfigurationProperties 和 @PropertySource 读取配置文件,将参数加载成实例属性。

@Component
@ConfigurationProperties(prefix = UrlConfig.PREFIX)
@PropertySource("classpath:baseConfig.properties")
public class UrlConfig {
    public static final String PREFIX = "config";

    private String serverUrl;
    private String getFileDir;

    private String token;

    public void setToken(String token) {
        this.token = token;
    }
    public String getToken() {
        return token;
    }
    public void setServerUrl(String serverUrl) {
        this.serverUrl = serverUrl;
    }
    public String getServerUrl() {
        return serverUrl;
    }
    public void setGetFileDir(String getFileDir) {
        this.getFileDir = getFileDir;
    }
    public String getGetFileDir() {
        return getFileDir;
    }

一个简单的demo就轻松实现了客户端向服务端定时发送文件的定时任务功能。不得不感慨SpringBoot的强大之处。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,563评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,263评论 25 707
  • 没有了约束之后,人自然地就倦怠下来。 每每想起自己承诺的事情没有做到,心里就内疚不已。可是写作这事情,要是没有养成...
    丁零花阅读 223评论 0 0
  • 已经参加简书一周期,每一天,为了完成作业,拿回我的本金,真的是拼了老命。但我发现,真的有内容可写的日子,...
    犹佑阅读 373评论 0 0