如何配置google-cloud-cpp的Datastore连接Firebase Firestore模拟器?
配置google-cloud-cpp Datastore客户端连接Firestore模拟器
问题描述
我正在使用google-cloud-cpp的Datastore,当前同项目下运行着Firestore模拟器。我的Datastore API采用原生模式(即Firestore),相关代码如下:
// namespace FIRESTORE = google::cloud::FIRESTORE; template <typename ModelType> class Firestore { public: // Constructor Firestore() { auto &app = drogon::app(); auto customConfig = app.getCustomConfig(); project_id = customConfig.get("gcloud_project_id", "default-project").asString(); // Initialize the Firestore client with the necessary connection google::cloud::Options options; // Specify the emulator endpoint. This URL is just an example; adjust the port as needed. //std::string emulator_endpoint = "http://localhost:9019"; // Create client options with the emulator endpoint //auto options = google::cloud::datastore_v1::ClientOptions::CreateDefaultClientOptions().value(); //options.set(emulator_endpoint); // options.set<google::cloud::ProjectIdOption>(project_id); client_ = std::make_unique<google::cloud::datastore_v1::DatastoreClient>( google::cloud::datastore_v1::MakeDatastoreConnection()); }; // ... 其他成员 private: std::unique_ptr<google::cloud::datastore_v1::DatastoreClient> client_; std::string project_id; };
想请教是否可以配置使其使用本地模拟器,以及能否连接到Firebase Firestore模拟器?
解决方案
完全可以配置Datastore客户端连接本地Firebase Firestore模拟器,因为Datastore原生模式与Firestore API兼容,google-cloud-cpp的Datastore客户端支持通过两种方式实现:
方式一:环境变量配置(无需修改代码)
启动Firestore模拟器后,终端会输出类似如下的环境变量设置提示:
export FIRESTORE_EMULATOR_HOST=localhost:8080
在运行你的C++程序前,先设置这个环境变量。google-cloud-cpp的Datastore客户端会自动识别该变量,将所有请求转发到本地模拟器,无需修改现有代码。
方式二:代码硬编码配置(灵活可控)
修改构造函数中的客户端初始化逻辑,明确指定模拟器端点、项目ID并禁用认证:
// namespace FIRESTORE = google::cloud::FIRESTORE; template <typename ModelType> class Firestore { public: // Constructor Firestore() { auto &app = drogon::app(); auto customConfig = app.getCustomConfig(); project_id = customConfig.get("gcloud_project_id", "default-project").asString(); // 配置模拟器端点(替换为你的模拟器实际端口,默认Firestore模拟器是8080) std::string emulator_endpoint = "http://localhost:8080"; google::cloud::Options options; // 设置模拟器端点 options.set<google::cloud::EndpointOption>(emulator_endpoint); // 设置项目ID options.set<google::cloud::ProjectIdOption>(project_id); // 禁用认证(模拟器不需要OAuth2凭证) options.set<google::cloud::UnifiedCredentialsOption>( google::cloud::MakeInsecureCredentials()); // 创建带配置的连接和客户端 client_ = std::make_unique<google::cloud::datastore_v1::DatastoreClient>( google::cloud::datastore_v1::MakeDatastoreConnection(options)); }; // ... 其他成员 private: std::unique_ptr<google::cloud::datastore_v1::DatastoreClient> client_; std::string project_id; };
注意事项
- 确保Firestore模拟器已启动,且代码中的端口与模拟器实际端口一致(默认Firestore模拟器端口为8080)。
- 项目ID需与启动模拟器时指定的项目ID一致(若启动未指定,默认使用代码中的"default-project"即可)。
- 必须禁用认证,否则客户端会尝试向Google Cloud发送认证请求,导致连接模拟器失败。
内容的提问来源于stack exchange,提问作者Ericel
相关产品推荐
相关产品推荐

