5. Implement async task
Trong phần này, chúng ta sẽ tìm hiểu cách triển khai tác vụ bất đồng bộ (asynchronous) trong ứng dụng Spring Boot của chúng ta. Tác vụ bất đồng bộ cho phép chúng ta thực hiện các công việc trong nền mà không làm chậm trễ các yêu cầu khác.
Cấu hình
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class AsyncConfig {
}
Áp dụng
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async
public void performAsyncTask() {
System.out.println("⏰ Async task started at: " + System.currentTimeMillis());
try {
Thread.sleep(5000); // Simulate long-running task
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("✅ Async task completed at: " + System.currentTimeMillis());
}
}
import com.example.demo.services.BackgroundService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BackgroundController {
private final BackgroundService backgroundService;
public BackgroundController(BackgroundService backgroundService) {
this.backgroundService = backgroundService;
}
@GetMapping("/start-task")
public String startBackgroundTask() {
backgroundService.performBackgroundTask();
return "Task is being processed in the background.";
}
}
Kết luận
Việc dùng @Async trong Spring Boot giúp chúng ta dễ dàng triển khai các tác vụ bất đồng bộ mà không cần phải can thiệp thủ công. Chúng ta có thể định nghĩa các tác vụ này bằng cách sử dụng các annotation đơn giản và cấu hình thời gian thực hiện một cách linh hoạt.
Bạn có thể gọi phương thức performAsyncTask()
từ bất kỳ đâu trong ứng dụng của bạn, và nó sẽ chạy trong nền mà không làm chậm trễ các yêu cầu khác. Điều này rất hữu ích cho các tác vụ tốn thời gian như gửi email, xử lý dữ liệu lớn, hoặc gọi API bên ngoài.