Bắt đầu ngayBắt đầu miễn phí

Triển khai pipeline xử lý dữ liệu bất đồng bộ

Bạn đang xây dựng một bảng điều khiển phân tích cần lấy dữ liệu người dùng và nhật ký hoạt động từ các dịch vụ riêng biệt, sau đó xử lý chúng để tạo bản tóm tắt người dùng. Thao tác này cần được thực hiện bất đồng bộ để ứng dụng luôn phản hồi tốt. Nhiệm vụ của bạn là triển khai điều này bằng CompletableFuture.

Các lớp UserDataUserSummary đã được nạp sẵn cho bạn.

Bài tập này là một phần của khóa học

Tối ưu hóa mã trong Java

Xem khóa học

Hướng dẫn bài tập

  • Thêm bước lấy dữ liệu người dùng trong CompletableFuture.
  • Thêm bước xử lý dữ liệu người dùng trong CompletableFuture.
  • Thêm xử lý ngoại lệ trong CompletableFuture.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

public class AsyncDashboard {
    public static void main(String[] args) throws Exception {        
        CompletableFuture userSummaryFuture = CompletableFuture
            // Fetch the user data
            .____(() -> fetchUserData("user123"))
            
            // Create summary based on fetched data
            .____(userData -> createSummary(userData))
            
            // Add exception handling
            .____(ex -> new UserSummary(new UserData("error", "Error User"))); 
        Thread.sleep(5000);
    }
    
    private static UserData fetchUserData(String userId) {
        simulateNetworkLatency(300);
        return new UserData(userId, "John Doe");
    }
    
    private static UserSummary createSummary(UserData userData) {
        simulateNetworkLatency(200);
        return new UserSummary(userData);
    }
    
    private static void simulateNetworkLatency(int millis) {
        try { Thread.sleep(millis); } catch (InterruptedException e) {}
    }
}
Chỉnh sửa và Chạy Mã