Cloud Functions 中的 Cloud Spanner 会话处理

Cloud Spanner session handling in Cloud Functions

我正在使用 Cloud Functions 和 nodeJS 客户端库将数据插入 Spanner。该函数由Pub/sub调用约2times/sec,并使用事务插入数据。

阅读文档时,它清楚地表明您必须通过调用以下方式关闭会话:database.close(); 当我这样做时,它会抛出一个错误:

Error: Database is closed. at SessionPool.<anonymous>   
(/srv/node_modules/@google-cloud/spanner/build/src/session-   
pool.js:264:23)
at Generator.next (<anonymous>) at /srv/node_modules/@google-
cloud/spanner/build/src/session-pool.js:22:71 at new Promise
(<anonymous>) at __awaiter (/srv/node_modules/@google-
cloud/spanner/build/src/session-pool.js:18:12) at SessionPool._acquire 
(/srv/node_modules/@google-cloud/spanner/build/src/session-
pool.js:262:16) at SessionPool.getReadSession 
(/srv/node_modules/@google-cloud/spanner/build/src/session-
pool.js:204:14) at Database.runStream (/srv/node_modules/@google-
cloud/spanner/build/src/database.js:1157:20) at Database.run 
(/srv/node_modules/@google-cloud/spanner/build/src/database.js:988:14) 
at PromiseCtor (/srv/node_modules/@google-
cloud/promisify/build/src/index.js:71:28)

所以我的问题是:Spanner 会话在 Cloud Functions 中的处理方式不同吗?它是否为下次调用缓存会话? 我做错了什么,我不应该在云函数中调用 database.close() 吗?

我在返回 transaction.commit() 和调用 transaction.end() 之后调用 database.close();

谢谢!

正如您在评论中提到的,每次都会创建一个新会话,the docs 中提到了这一点。

还有tutorial you mentioned has no database.close() ran correctly on my side, so i took a look at the docs on Cloud Functions and Cloud SQL,这里写着:

we recommend that you not close connections at the end of the function call. If you do not use a pool in global scope, and/or if you create individual connections in function-scope, then you should close these connections before the function returns.

所以这应该适用于任何连接,包括 spanner