Others_1_Asynchronous

hayeka發表於2020-03-08

service/AsyncService

package cn.boxku.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * ————————————————————————————————————————————————
 * CREATED BY hayeka ON 2020/3/8 16:38
 * ————————————————————————————————————————————————
 */
@Service
public class AsyncService {


    //告訴spring這是一個非同步的方法
    @Async
    public void hello()
    {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("資料正在處理......");
    }

}

controller/HelloController

package cn.boxku.controller;

import cn.boxku.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * ————————————————————————————————————————————————
 * CREATED BY hayeka ON 2020/3/8 16:39
 * ————————————————————————————————————————————————
 */
@RestController
public class HelloController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello()
    {
            asyncService.hello();
            return "ok";
    }
}

AsynchronousApplication入口

package cn.boxku;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class AsynchronousApplication {

    public static void main(String[] args) {
        SpringApplication.run(AsynchronousApplication.class, args);
    }

}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

一個從事軟體開發職業的經濟愛好者