如何在AWS lambda中等待(Firebase)回调?

时间:2017-04-21 10:12:54

标签: java amazon-web-services firebase callback aws-lambda

我一直在寻找类似的问题,但据我所知,这些问题都与Java无关。 我想调用AWS lambda函数,我在其中连接到Firebase数据库。问题是处理程序在从Firebase获取所需数据之前执行。

@Override
public String handleRequest(Request input, Context context) {
    try {
        FileInputStream serviceAccountInputStream = new FileInputStream(FIREBASE_SERVICE_ACCOUNT_CREDENTIALS_PATH);

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredential(FirebaseCredentials.fromCertificate(serviceAccountInputStream))
                .setDatabaseUrl(FIREBASE_DATABASE_URL)
                .build();
        FirebaseApp.initializeApp(options);

        DatabaseReference ref = FirebaseDatabase
                .getInstance()
                .getReference("users/" + input.getUid());
        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                System.out.print(dataSnapshot);
                // TODO: Do computations on data and return results
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.print("Canceled");
                // TODO: Return error
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
    // TODO: Return computed results
    return "This could be the start of something new.";
}

我需要从Firebase数据库中读取数据,对其进行一些计算并将计算结果返回给用户。我怎样才能做到这一点? :)

1 个答案:

答案 0 :(得分:1)

您可以使用CountDownLatch等待异步代码完成。

在调用异步代码之前,您需要创建CountDownLatch:

final CountDownLatch countDownLatch = new CountDownLatch(1);

然后在回调方法结束时,你倒数一下锁存器:

countDownLatch.countDown();

然后在异步方法之后等待CountDownLatch倒计时:

waitForCountdownLatch(countDownLatch);

private static void waitForCountdownLatch(CountDownLatch countDownLatch) {
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        log.error(e);
        e.printStackTrace();
    }
}

所以使用你的代码就是:

@Override
public String handleRequest(Request input, Context context) {

    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final Object[] singleValue = new Object[1];
    final DatabaseError[] firebaseError = new DatabaseError[1];

    try {
        FileInputStream serviceAccountInputStream = new FileInputStream(FIREBASE_SERVICE_ACCOUNT_CREDENTIALS_PATH);

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredential(FirebaseCredentials.fromCertificate(serviceAccountInputStream))
                .setDatabaseUrl(FIREBASE_DATABASE_URL)
                .build();
        FirebaseApp.initializeApp(options);

        DatabaseReference ref = FirebaseDatabase
                .getInstance()
                .getReference("users/" + input.getUid());

        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                System.out.print(dataSnapshot);
                Object snapshotValue = dataSnapshot.getValue();
                if(snapshotValue != null) {
                    singleValue[0] = snapshotValue;
                }
                countDownLatch.countDown();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.print("Canceled");
                firebaseError0] = databaseError;
                countDownLatch.countDown();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        countDownLatch.countDown();
    }

    waitForCountdownLatch(countDownLatch);
    if(firebaseError[0] != null) {
        System.out.print(firebaseError[0].toException().getMessage());
    }
    if(singleValue[0] != null) {
        // do something with result
    }
    return "This could be the start of something new.";
}

private void waitForCountdownLatch(CountDownLatch countDownLatch) {
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        log.error(e);
        e.printStackTrace();
    }
}