简体   繁体   中英

Java application cannot find credentials to access GCP Pub/Sub

I'm attempting to use the GCP Java SDK to send messages to a Pub/Sub topic using the following code (replaced the actual project ID and topic name with placeholders in this snippet):

Publisher publisher = null;
ProjectTopicName topic = ProjectTopicName.newBuilder()
        .setProject("MY_PROJECT_ID")
        .setTopic("MY_TOPIC")
        .build();

try {
    publisher = Publisher.newBuilder(topic).build();

    for (final String message : data) {
        ByteString messageBytes = ByteString.copyFromUtf8(message);
        PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(messageBytes).build();
        ApiFuture<String> future = publisher.publish(pubsubMessage);
    }
} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (publisher != null) {
        publisher.shutdown();
    }
}

This results in the following exception:

Exception in thread "main" java.lang.AbstractMethodError: com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.needsCredentials()Z
    at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:157)
    at com.google.cloud.pubsub.v1.stub.GrpcPublisherStub.create(GrpcPublisherStub.java:164)
    at com.google.cloud.pubsub.v1.Publisher.<init>(Publisher.java:171)
    at com.google.cloud.pubsub.v1.Publisher.<init>(Publisher.java:85)
    at com.google.cloud.pubsub.v1.Publisher$Builder.build(Publisher.java:718)
    at com.westonsankey.pubsub.MessageWriter.sendMessagesToPubSub(MessageWriter.java:35)
    at com.westonsankey.pubsub.MessageWriter.main(MessageWriter.java:24)

I've set the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to the JSON private key file, and have confirmed that I can access other GCP resources in this application using that private key. The service account has project owner, and I've verified via the Pub/Sub console that the service account has the appropriate permissions.

Are there any extra steps required to authenticate with Pub/Sub?

The problem isn't accessing the credentials. It looks like this is a version conflict on the gax-java library. The needsCredentials method was added in v1.46 in June 2019. Perhaps you are explicitly depending on an older version or another dependency is pulling in an older version and is leaking the version they pull in. If it's the former, update to pull in version 1.46 or later. If it's the latter, you may need to shade the dependency .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM