這工作,但PubSub的客戶端需要與端口模擬器是正確配置使用。
這是我用來創建PubSub客戶端的代碼。它基於PubSub Sample。注意setRootUrl部分。
private Pubsub getClient(final HttpTransport httpTransport, final JsonFactory jsonFactory) {
Preconditions.checkNotNull(httpTransport);
Preconditions.checkNotNull(jsonFactory);
GoogleCredential credential = null;
try {
credential = GoogleCredential.getApplicationDefault();
} catch (IOException e) {
e.printStackTrace();
}
if (credential.createScopedRequired()) {
credential = credential.createScoped(PubsubScopes.all());
}
// Please use custom HttpRequestInitializer for automatic
// retry upon failures.
HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
Pubsub.Builder pubsubBuilder = new Pubsub.Builder(httpTransport, jsonFactory, initializer);
pubsubBuilder.setApplicationName("<your project id>");
//Check if this is localhost
if (SystemProperty.environment.value() != SystemProperty.Environment.Value.Production) {
pubsubBuilder.setRootUrl("http://localhost:8321/");
}
return pubsubBuilder.build();
}
然後通過使用啓動模擬器:
gcloud測試模擬器發佈訂閱開始--host端口=本地主機:8321
實際端口號並不重要。當然,每次重新啓動模擬器時,主題和訂閱都需要通過代碼進行配置。
正是我正在尋找的......在構建客戶端並使用專用端口啓動模擬器時將其設置在代碼中。 –