如何将 Google Cloud Library for Datastore 连接到 App Engine 开发服务器?

How to connect Google Cloud Library for Datastore to the App Engine development server?

我们正计划从 Java 8 的 Google App Engine 标准环境中迁移一个内部应用 运行,也是为了允许移植到其他执行环境。

除了缺少 IN/OR 查询运算符的一系列问题外,我们还在为本地测试设置而苦苦挣扎:根据 Using the Java 8 Local Development Server

The development web server simulates Datastore using a local file-backed Datastore on your computer. The Datastore is named local_db.bin, and it is created in your application's WAR directory, in the WEB-INF /appengine-generated/ directory.

但我们不知道如何将 Google Cloud Client Library for Datastore 连接到本地模拟器。

使用

定义默认凭据
gcloud auth application-default login

或在使用类似

的服务帐户获取凭据后设置 GOOGLE_APPLICATION_CREDENTIALS 环境变量
gcloud iam service-accounts keys create key.json \
    --iam-account=project-id@appspot.gserviceaccount.com

如其他地方所建议的那样,根据 ADC 策略,只会导致客户端库连接到实际的云服务器,而不是连接到本地模拟器。

我希望开发服务器自动向客户端库提供连接提示,但显然不是这样。

关于设置本地测试环境的任何建议,考虑到我们不能只迁移到独立的 Datastore Emulator,因为我们需要目前仅由 App Engine 开发服务器提供的其他服务(例如电子邮件提交)?


编辑 / 进一步修改后,我们通过使用本地开发服务器和独立的数据存储模拟器来解决这个问题:

gcloud beta emulators datastore start \
  —project=project-id \
  --host-port=localhost:8081 \
  --data-dir=target/war

DATASTORE_EMULATOR_HOST=localhost:8081 java_dev_appserver.sh \
 --port=8080 \
 target/war

但是,该过程非常繁琐且难以自动化:我们正在寻找一种方法来自动将 Google Client Library 连接到由 Java 8 Local Development 管理的 Datastore Emulator使用 App Engine Maven plugin 之类的内容启动应用程序时的服务器,例如mvn appengine:run.

GitHub issue 已关闭,确认数据存储客户端库与本地 Web 服务器数据存储模拟器不兼容。

我真的试过了,看看是否可以强制连接到本地 Web 服务器。下面的代码设置了一个具有所需主机配置的自定义构建器:

DatastoreOptions.Builder builder = DatastoreOptions.newBuilder();
builder.setHost("http://localhost:8080");
builder.setProjectId("<PROJECT_ID>");

Datastore ds = builder.build().getService();

Key key = ds.newKeyFactory().setKind("MyEntity").newKey("mykey");
Entity entity = Entity.newBuilder(key).set("p1", "Hello World!").build();

entity = ds.put(entity);
System.out.println(entity);

entity = ds.get(key);
System.out.println(entity);

在 运行 本地 Web 服务器之后,我注意到确实可以建立连接,但是数据存储客户端库在尝试存储新实体时返回以下错误:

[INFO] GCLOUD: com.google.cloud.datastore.DatastoreException: Non-protobuf error: <html><head><title>Error 404</title></head>|<body><h2>Error 404</h2></body>|</html>. HTTP status code was 404.

Web 服务器输出以下内容:

Oct 02, 2019 3:05:59 PM com.google.appengine.tools.development.jetty9.LocalResourceFileServlet doGet
WARNING: No file found for: /v1/projects/<PROJECT_ID>:commit

我相信这进一步证实了新库与旧模拟器不兼容。

当您 work/wait 完全迁移到 Datastore 模式模拟器时,您找到的解决方法可能是最佳解决方案。