寫在前面:2020年面試必備的Java後端進階面試題總結了一份複習指南在Github上,內容詳細,圖文並茂,有需要學習的朋友可以Star一下!
GitHub地址:https://github.com/abel-max/Java-Study-Note/tree/master
(一)異步任務
異步任務的需求在實際開發場景中經常遇到,Java實現異步的方式有很多,比如多線程實現異步。在SpringBoot中,實現異步任務只需要增加兩個註解就可以實現。當前類添加@Async註解,啓動類添加@EnableAsync
編寫一個service,AsynService,讓這個服務暫停3秒後再輸出數據
@Service
public class AsynService {
@Async
public void async(){
try {
Thread.sleep(3000);
System.out.println("執行結束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
編寫controller,調用這個服務類
@RestController
public class IndexController {
@Autowired
public AsynService asynService;
@RequestMapping("/index")
public String asynctask(){
asynService.async();
return "async task";
}
}
運行後在瀏覽器中訪問http://localhost:8080/index ,會發現由於開啓了異步,瀏覽器中會先輸出async task,過了三秒後控制檯纔會輸出執行結束。
(二)定時任務
我在之前的秒殺開源項目中已經使用過定時任務,當時的場景時,每隔1分鐘去輪詢數據庫查詢過期的商品。定時任務的應用範圍很廣,比如每天12點自動打包日誌,每天晚上12點備份等等。 在SpringBoot實現定時任務也只需要兩個註解:@Scheduled和@EnableScheduling 和前面一樣,@Scheduled用在需要定時執行的任務上,@EnableScheduling用在啓動類上。 首先來編寫定時任務類:
@Service
public class ScheduleService {
@Scheduled(cron = "0/10 * * * * ? ")
public void sayHello(){
System.out.println("hello");
}
}
@Scheduled註解中需要加入cron表達式,用來判斷定時任務的執行時間,這裏表示每10秒執行一次。
然後在啓動類中加上註解@EnableScheduling。 運行項目,會發現每隔十秒會輸出一條hello。