I am trying to create a separate class just to connect to GCPPUB.I have following class which successfully connects and push messages to gcp. But the problem is every time it validates the connection from my app using GCP Credentials. I want to get connection once after that publish messages continuously?Is there a way, I can separate my code so that get connection only if the existing connection is null and publish messages there after?And it it right way to get only one connection?
@Slf4j
public class GCPMessagePublisher {
private static final String PROJECT_ID = "myprojectId";
Publisher publisher = null;
public void putMessageOnGCP(String message) throws Exception
{
log.info("The outgoing message to GCP PUBSUB is : "+message);
// topic id, eg. "my-topic"
String topicId = "topic_name";
int messageCount = 10;
ProjectTopicName topicName = ProjectTopicName.of(PROJECT_ID, topicId);
List<ApiFuture<String>> futures = new ArrayList<>();
try {
GoogleCredentials credentials = GoogleCredentials.fromStream(
new FileInputStream("gcp credential here ........"));
publisher = publisher.newBuilder(topicName).setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();
for (int i = 0; i < messageCount; i++) {
// convert message to bytes
ByteString data = ByteString.copyFromUtf8(message);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder()
.setData(data)
.build();
// Schedule a message to be published. Messages are automatically batched.
ApiFuture<String> future = publisher.publish(pubsubMessage);
futures.add(future);
}
} finally {
// Wait on any pending requests
List<String> messageIds = ApiFutures.allAsList(futures).get();
for (String messageId : messageIds) {
System.out.println(messageId);
}
if (publisher != null) {
// When finished with the partypublisher, shutdown to free up resources.
publisher.shutdown();
}
}
}
}