SpringBoot之異步調用

第一步:創建項目,添加依賴

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

第二步:創建業務模擬類

@Service
public class MsgService {
    public void sth1() {
        System.out.println("--------sth1 start--------");
        for (int i = 0; i < 4; i++) {
            System.out.println("***************** " + i);
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("--------sth1 end--------");
    }
    @Async
    public void sth2() {
        System.out.println("--------sth2 start--------");
        for (int i = 0; i < 4; i++) {
            System.out.println("***************** " + i);
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("--------sth2 end--------");
    }
}

第三步:定義Controller

@Controller
@RequestMapping("/index")
public class IndexController {
    @Autowired
    private MsgService msgService;
    @RequestMapping("/fun1")
    public void fun1() {
        System.out.println("--------fun1 start--------");
        msgService.sth1();
        System.out.println("--------fun1 end--------");
    }
    @RequestMapping("/fun2")
    public void fun2() {
        System.out.println("--------fun2 start--------");
        msgService.sth2();
        System.out.println("--------fun2 end--------");
    }
}

第四步:爲springboot的啓動類加上@EnableAsync

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

啓動項目,打開網頁測試:

  • http://localhost/async/index/fun1
    在這裏插入圖片描述
  • http://localhost/async/index/fun2
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章