Springboot做一個(gè)定時(shí)任務(wù)(客戶端和服務(wù)端)

目標(biāo)效果圖效果圖:


客戶端向服務(wù)端定時(shí)任務(wù)發(fā)送文件

最近在學(xué)習(xí)SpringBoot項(xiàng)目,項(xiàng)目模塊中有用到一些,做一個(gè)定時(shí)任務(wù)調(diào)度的功能,使用restful來簡單實(shí)現(xiàn)一下。

實(shí)現(xiàn)步驟

選擇Create NewProject 創(chuàng)建一個(gè)新工程

選擇Spring Initializr

springboot項(xiàng)目

創(chuàng)建一個(gè)工程,工程下面可以分模塊子模塊構(gòu)建依賴maven構(gòu)建的生態(tài)

創(chuàng)建工程名

這里可以添加許多依賴模塊包,提供為開發(fā)者更大的簡便,不用的自己配置復(fù)雜的配置文件,用著就是爽

選擇添加的模塊
創(chuàng)建模塊工程名

工程創(chuàng)建成功后將配置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請(qǐng)求所需包  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啟動(dòng)包-->
        <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>
            <!-- 可命令行獨(dú)立編譯maven項(xiàng)目下的class文件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <proc>none</proc>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

工程目錄結(jié)構(gòu)如下


工程目錄結(jié)構(gòu)

下面我們配置一下定時(shí)任務(wù)
啟動(dòng)類中假如 @EnableScheduling 注解來開啟任務(wù)調(diào)度

@SpringBootApplication
@EnableScheduling
public class SpringErnestfeiTimertaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringErnestfeiTimertaskApplication.class, args);
        System.out.println("=======================Springboot實(shí)現(xiàn)定時(shí)任務(wù)客戶端demo=========================");
    }
}

調(diào)度方法如下

@Component
public class TimerTasks {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    @Resource
    private UrlConfig config;
    /**
     * 定時(shí)任務(wù)上傳文件到服務(wù)器
     * */
    @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("{客戶端定時(shí)任務(wù)開啟每一分鐘發(fā)送一次}===>>>"+dateFormat.format(date));
    }
}

使用HttpClinet實(shí)現(xiàn)客戶端調(diào)度,具體如下

    /**
     * 上傳文件
     *  serverUrl 上傳服務(wù)器地址
     *  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("====開始執(zhí)行====" + 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("====結(jié)束執(zhí)行====" + endTime);
                System.out.println("====執(zhí)行時(shí)間====" + (endTime - startTime));
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            System.out.println("====服務(wù)器端無法連接異常====");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("====服務(wù)器端無法連接異常====");
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

服務(wù)端Contoller層處理客戶端調(diào)用處理

@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("{服務(wù)端接受內(nèi)容}===>>>"+content);
        if(token.equals(config.getToken())){
            System.out.println("{上傳的文件名為}===>>>"+file.getOriginalFilename());
            resMap.put("status",200);
            resMap.put("message","服務(wù)端返回=上傳成功,返回文件"+file.getOriginalFilename());
        }else{
            resMap.put("status",400);
            resMap.put("message","服務(wù)端返回=上傳失敗,TOKEN校驗(yàn)失敗!");
        }
        return JSON.toJSONString(resMap);
    }
}

讀取配置文件中的參數(shù)可以使用@ConfigurationProperties 和 @PropertySource 讀取配置文件,將參數(shù)加載成實(shí)例屬性。

@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;
    }

一個(gè)簡單的demo就輕松實(shí)現(xiàn)了客戶端向服務(wù)端定時(shí)發(fā)送文件的定時(shí)任務(wù)功能。不得不感慨SpringBoot的強(qiáng)大之處。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,885評(píng)論 6 541
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,312評(píng)論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,993評(píng)論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,667評(píng)論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,410評(píng)論 6 411
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,778評(píng)論 1 328
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,775評(píng)論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,955評(píng)論 0 289
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,521評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,266評(píng)論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,468評(píng)論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,998評(píng)論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,696評(píng)論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,095評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,385評(píng)論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,193評(píng)論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,431評(píng)論 2 378

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,823評(píng)論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,715評(píng)論 25 708
  • 沒有了約束之后,人自然地就倦怠下來。 每每想起自己承諾的事情沒有做到,心里就內(nèi)疚不已。可是寫作這事情,要是沒有養(yǎng)成...
    丁零花閱讀 226評(píng)論 0 0
  • 已經(jīng)參加簡書一周期,每一天,為了完成作業(yè),拿回我的本金,真的是拼了老命。但我發(fā)現(xiàn),真的有內(nèi)容可寫的日子,...
    猶佑閱讀 411評(píng)論 0 0