无法从云功能连接到 firebase 实时数据库(java)

No connection to firebase realtime database from cloud functions (in java)

我在 Google Cloud Functions(在 Java)中部署了一个函数,在尝试访问实时数据库时,根本没有任何响应 - 唯一的提示是我通话:

query.addListenerForSingleValueEvent

我看到一个日志条目:

Failed to find a usable hardware address from the network interfaces; using random bytes: f1:81:5a:ef:89:81:63:07

这是我的代码(该函数是通过从队列接收消息触发的):

public class FetchGPWFunction implements BackgroundFunction<PubSubMessage> {
    private static final Logger logger = Logger.getLogger(FetchGPWFunction.class.getName());

    @Override
    public void accept(PubSubMessage message, Context context) {
        String data = message.data != null
                ? "Step 0.1 successful! with message: " + new String(Base64.getDecoder().decode(message.data))
                : "Step 0.1 successful!";
        logger.info(data);
        testFetchData();
    }

    private void testFetchData() {
        if (FirebaseApp.getApps().isEmpty()) {
            FirebaseApp.initializeApp();
            logger.info("Firebase application has been initialized");
        }
        DatabaseReference databaseReference = FirebaseDatabase.getInstance("https://projectid-rtdb.europe-west1.firebaseio.com").getReference();
        Query query = databaseReference.
                child("stockData").
                child("daily").
                child("pl").
                child("ALE").
                child("quotations").
                child("20201012").
                child("high");
        logger.info("launch query");
        final QueryResult queryResult = new QueryResult();
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                logger.info("onDataChange >> got key=" + dataSnapshot.getKey() + " with value=" + dataSnapshot.getValue());
                queryResult.setDataSnapshot(dataSnapshot);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                logger.severe("onCancelled >> ERROR! " + databaseError.getMessage() + " details=" + databaseError.getDetails());
                queryResult.setError(databaseError);
            }
        });

        int loopSafeGuard = 40;
        try {
            while (!queryResult.isDone() && (loopSafeGuard > 0)) {
                Thread.sleep(500);
                loopSafeGuard--;
            }
            logger.info("Loop ended with results: dataSnapshot=" + queryResult.getDataSnapshot() + " error=" + queryResult.getError());
        } catch (InterruptedException ie) {
            logger.info("Sleeping interrupted");
        }
    }

    public static class PubSubMessage {
        String data;
        Map<String, String> attributes;
        String messageId;
        String publishTime;
    }
}

(查询结果只是一个wrapper:

public class QueryResult {
    private DataSnapshot dataSnapshot = null;
    private DatabaseError error = null;
    
   ...
   
    public boolean isDone() {
        return ((dataSnapshot != null) || (error != null));
    }
}

这是日志:

Info 2021-10-21 10:25:26.377 CEST functionFetchGPWData Firebase application has been initialized
Info 2021-10-21 10:25:26.420 CEST functionFetchGPWData launch query
Warning 2021-10-21 10:25:26.829 CEST functionFetchGPWData Failed to find a usable hardware address from the network interfaces; using random bytes: f1:81:5a:ef:89:81:63:07
Info 2021-10-21 10:25:46.463 CEST functionFetchGPWData Loop ended with results: dataSnapshot=null error=null
Debug 2021-10-21 10:25:46.467 CEST Function execution took 21311 ms, finished with status: 'ok'

没有错误,没有异常! - 只是这个奇怪的警告:

{
  "insertId": "000000-93ea514e-7271-4fe1-8b71-672b7d028ef7",
  "jsonPayload": {
    "message": "Failed to find a usable hardware address from the network interfaces; using random bytes: f1:81:5a:ef:89:81:63:07",
    "logging.googleapis.com/sourceLocation": {
      "method": "defaultMachineId",
      "file": "io/netty/util/internal/MacAddressUtil.java"
    }
  },
  "resource": {
    "type": "cloud_function",
    "labels": {
      "function_name": "functionFetchGPWData",
      "project_id": "projectid",
      "region": "europe-central2"
    }
  },
  "timestamp": "2021-10-21T08:25:26.829Z",
  "severity": "WARNING",
  "labels": {
    "execution_id": "waz43dlcibiy"
  },
  "logName": "projects/projectid/logs/cloudfunctions.googleapis.com%2Fcloud-functions",
  "trace": "projectid/traces/b812907333b0200b82f1323a1b5f7dcd",
  "sourceLocation": {
    "file": "io/netty/util/internal/MacAddressUtil.java"
  },
  "receiveTimestamp": "2021-10-21T08:25:35.103281657Z"
}

这是云函数中的错误吗?我做错了什么(更有可能;))。我不相信一个简单的实时数据库读取需要超过 20 秒。

总结一下,这是 Cloud Functions 冷启动的另一个例子。

虽然有时无法完全摆脱冷启动,但您可以遵循一些 GCP recommendations 可能有助于减少这种影响的方法。