java 8 CompletableFuture (2)

package com.example.demo.future;

import java.util.UUID;
import java.util.concurrent.CompletableFuture;

public class FutureTest {


    /**
     * 獲取門店id
     *
     * @return
     */
    private static Long getStoreId() {
        try {

            Thread.sleep(1500); //擬處理遠程處理時間
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Math.round(Math.random() * 10000);
    }

    /**
     * 根據門店Id獲取訂單數據
     *
     * @return
     */
    private static String getData(String sign) {
        try {

            Thread.sleep(1500); //擬處理遠程處理時間
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return String.format("{storeId:%s,orderNo:'%s',sign:%s}",
                Math.round(Math.random() * 10000), UUID.randomUUID().toString(), sign);
    }


    public static void main(String[] args) {

        CompletableFuture<String> orderFuture = CompletableFuture
                .supplyAsync(FutureTest::getStoreId)   //第一步,從遠程先獲取門店id
                .thenApply(Long::toHexString)    //第二步,將門店id進行簽名
                .thenCompose(sign -> CompletableFuture.supplyAsync(() -> getData(sign)));  //第三步,從遠程獲取訂單數據


    }
}
相關文章
相關標籤/搜索