在springboot上經過CompletableFuture實現多異步任務合併彙總

@Service
public class WorkAsyncService {

    @Async
    public CompletableFuture<String> doWork(String value){

        System.out.println("--------start work------" + Thread.currentThread().getName());
        try {
            Thread.sleep(4000);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("-------end work----------");
        return CompletableFuture.completedFuture(value);
    }

}




@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoApplicationTests {


    @Autowired
    private WorkAsyncService workAsyncService;

    @Test
    public void asyncTest() throws Exception {

        List<CompletableFuture> cfList = Stream.of("h1", "h2", "h3", "h4").map(v -> {
            return workAsyncService.doWork(v);
        }).collect(Collectors.toList());

        StringBuilder sb = new StringBuilder();
        CompletableFuture rs = CompletableFuture.allOf(cfList.toArray(new CompletableFuture[cfList.size()])).whenComplete((v, t) -> {
            cfList.forEach(cf -> {
                sb.append(cf.getNow(null)).append(",");
            });
        });

        try {
            rs.get(6, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("------------------------" + sb.toString());

    }

}

一、經過@Async實現異步  (記得在啓動類添加@EnableAsync、@Async("myExecutor")指定用本身的線程池)java

二、CompletableFuture.allOf全部任務執行結束後進行彙總app

相關文章
相關標籤/搜索