use of org.springframework.cloud.gcp.pubsub.core.PubSubTemplate in project spring-cloud-gcp by spring-cloud.
the class PubSubTemplateDocumentationTests method subscribeSimpleTest.
@Test
public void subscribeSimpleTest() {
pubSubTest((PubSubTemplate pubSubTemplate, String subscriptionName, String topicName) -> {
pubSubTemplate.publish(topicName, "message");
Logger logger = new Logger();
// tag::subscribe[]
Subscriber subscriber = pubSubTemplate.subscribe(subscriptionName, (message) -> {
logger.info("Message received from " + subscriptionName + " subscription: " + message.getPubsubMessage().getData().toStringUtf8());
message.ack();
});
// end::subscribe[]
List<String> messages = logger.getMessages();
Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> !messages.isEmpty());
assertThat(messages).containsExactly("Message received from " + subscriptionName + " subscription: message");
});
}
use of org.springframework.cloud.gcp.pubsub.core.PubSubTemplate in project spring-cloud-gcp by spring-cloud.
the class PubSubHealthIndicatorAutoConfigurationTests method compositeHealthIndicatorPresentMultiplePubSubTemplate.
@Test
public void compositeHealthIndicatorPresentMultiplePubSubTemplate() {
PubSubTemplate mockPubSubTemplate1 = mock(PubSubTemplate.class);
PubSubTemplate mockPubSubTemplate2 = mock(PubSubTemplate.class);
this.baseContextRunner.withBean("pubSubTemplate1", PubSubTemplate.class, () -> mockPubSubTemplate1).withBean("pubSubTemplate2", PubSubTemplate.class, () -> mockPubSubTemplate2).withPropertyValues("management.health.pubsub.enabled=true").run(ctx -> {
assertThatThrownBy(() -> ctx.getBean(PubSubHealthIndicator.class)).isInstanceOf(NoSuchBeanDefinitionException.class);
CompositeHealthContributor healthContributor = ctx.getBean("pubSubHealthContributor", CompositeHealthContributor.class);
assertThat(healthContributor).isNotNull();
assertThat(healthContributor.stream()).hasSize(2);
healthContributor.stream().forEach(System.out::println);
assertThat(healthContributor.stream().map(c -> ((NamedContributor) c).getName())).containsExactlyInAnyOrder("pubSubTemplate1", "pubSubTemplate2");
});
}
use of org.springframework.cloud.gcp.pubsub.core.PubSubTemplate in project spring-cloud-gcp by spring-cloud.
the class PubSubTemplateIntegrationTests method testPubSubTemplateLoadsMessageConverter.
@Test
public void testPubSubTemplateLoadsMessageConverter() {
this.contextRunner.withUserConfiguration(JsonPayloadTestConfiguration.class).run((context) -> {
PubSubAdmin pubSubAdmin = context.getBean(PubSubAdmin.class);
PubSubTemplate pubSubTemplate = context.getBean(PubSubTemplate.class);
String topicName = "json-payload-topic" + UUID.randomUUID();
String subscriptionName = "json-payload-subscription" + UUID.randomUUID();
pubSubAdmin.createTopic(topicName);
pubSubAdmin.createSubscription(subscriptionName, topicName, 10);
TestUser user = new TestUser("John", "password");
pubSubTemplate.publish(topicName, user);
await().atMost(Duration.TEN_SECONDS).untilAsserted(() -> {
List<ConvertedAcknowledgeablePubsubMessage<TestUser>> messages = pubSubTemplate.pullAndConvert(subscriptionName, 1, true, TestUser.class);
assertThat(messages).hasSize(1);
TestUser receivedTestUser = messages.get(0).getPayload();
assertThat(receivedTestUser.username).isEqualTo("John");
assertThat(receivedTestUser.password).isEqualTo("password");
});
pubSubAdmin.deleteSubscription(subscriptionName);
pubSubAdmin.deleteTopic(topicName);
});
}
use of org.springframework.cloud.gcp.pubsub.core.PubSubTemplate in project spring-cloud-gcp by spring-cloud.
the class PubSubTemplateIntegrationTests method testCreatePublishPullNextAndDelete.
@Test
public void testCreatePublishPullNextAndDelete() {
this.contextRunner.run((context) -> {
PubSubAdmin pubSubAdmin = context.getBean(PubSubAdmin.class);
PubSubTemplate pubSubTemplate = context.getBean(PubSubTemplate.class);
String topicName = "tarkus_" + UUID.randomUUID();
String subscriptionName = "zatoichi_" + UUID.randomUUID();
assertThat(pubSubAdmin.getTopic(topicName)).isNull();
assertThat(pubSubAdmin.getSubscription(subscriptionName)).isNull();
pubSubAdmin.createTopic(topicName);
pubSubAdmin.createSubscription(subscriptionName, topicName);
Map<String, String> headers = new HashMap<>();
headers.put("cactuar", "tonberry");
headers.put("fujin", "raijin");
pubSubTemplate.publish(topicName, "tatatatata", headers).get();
// get message
AtomicReference<PubsubMessage> pubsubMessageRef = new AtomicReference<>();
Awaitility.await().atMost(30, TimeUnit.SECONDS).until(() -> {
pubsubMessageRef.set(pubSubTemplate.pullNext(subscriptionName));
return pubsubMessageRef.get() != null;
});
PubsubMessage pubsubMessage = pubsubMessageRef.get();
assertThat(pubsubMessage.getData()).isEqualTo(ByteString.copyFromUtf8("tatatatata"));
assertThat(pubsubMessage.getAttributesCount()).isEqualTo(2);
assertThat(pubsubMessage.getAttributesOrThrow("cactuar")).isEqualTo("tonberry");
assertThat(pubsubMessage.getAttributesOrThrow("fujin")).isEqualTo("raijin");
assertThat(pubSubAdmin.getTopic(topicName)).isNotNull();
assertThat(pubSubAdmin.getSubscription(subscriptionName)).isNotNull();
assertThat(pubSubAdmin.listTopics().stream().filter((topic) -> topic.getName().endsWith(topicName)).toArray().length).isEqualTo(1);
assertThat(pubSubAdmin.listSubscriptions().stream().filter((subscription) -> subscription.getName().endsWith(subscriptionName)).toArray().length).isEqualTo(1);
pubSubAdmin.deleteSubscription(subscriptionName);
pubSubAdmin.deleteTopic(topicName);
assertThat(pubSubAdmin.getTopic(topicName)).isNull();
assertThat(pubSubAdmin.getSubscription(subscriptionName)).isNull();
assertThat(pubSubAdmin.listTopics().stream().filter((topic) -> topic.getName().endsWith(topicName)).toArray().length).isEqualTo(0);
assertThat(pubSubAdmin.listSubscriptions().stream().filter((subscription) -> subscription.getName().endsWith(subscriptionName)).toArray().length).isEqualTo(0);
});
}
use of org.springframework.cloud.gcp.pubsub.core.PubSubTemplate in project spring-cloud-gcp by spring-cloud.
the class PubSubTemplateIntegrationTests method testPullAndAck.
@Test
public void testPullAndAck() {
this.contextRunner.run((context) -> {
PubSubAdmin pubSubAdmin = context.getBean(PubSubAdmin.class);
String topicName = "peel-the-paint" + UUID.randomUUID();
String subscriptionName = "i-lost-my-head" + UUID.randomUUID();
pubSubAdmin.createTopic(topicName);
pubSubAdmin.createSubscription(subscriptionName, topicName, 10);
PubSubTemplate pubSubTemplate = context.getBean(PubSubTemplate.class);
List<Future<String>> futures = new ArrayList<>();
futures.add(pubSubTemplate.publish(topicName, "message1"));
futures.add(pubSubTemplate.publish(topicName, "message2"));
futures.add(pubSubTemplate.publish(topicName, "message3"));
futures.parallelStream().forEach((f) -> {
try {
f.get(5, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException ex) {
LOGGER.error(ex);
Thread.currentThread().interrupt();
}
});
List<AcknowledgeablePubsubMessage> ackableMessages = new ArrayList<>();
Set<String> messagesSet = new HashSet<>();
for (int i = 0; i < 5 && messagesSet.size() < 3; i++) {
List<AcknowledgeablePubsubMessage> newMessages = pubSubTemplate.pull(subscriptionName, 4, false);
ackableMessages.addAll(newMessages);
messagesSet.addAll(newMessages.stream().map((message) -> message.getPubsubMessage().getData().toStringUtf8()).collect(Collectors.toList()));
}
assertThat(messagesSet.size()).as("check that we received all the messages").isEqualTo(3);
ackableMessages.forEach((message) -> {
try {
if (message.getPubsubMessage().getData().toStringUtf8().equals("message1")) {
// sync call
message.ack().get();
} else {
// sync call
message.nack().get();
}
} catch (InterruptedException | ExecutionException ex) {
LOGGER.error(ex);
Thread.currentThread().interrupt();
}
});
Thread.sleep(11_000);
// pull the 2 nacked messages with retries for up to 10s
int messagesCount = 0;
int tries = 100;
while (messagesCount < 2 && tries > 0) {
Thread.sleep(100);
ackableMessages = pubSubTemplate.pull(subscriptionName, 4, true);
ackableMessages.forEach((m) -> m.ack());
messagesCount += ackableMessages.size();
tries--;
}
assertThat(messagesCount).as("check that we get both nacked messages back").isEqualTo(2);
pubSubAdmin.deleteSubscription(subscriptionName);
pubSubAdmin.deleteTopic(topicName);
});
}
Aggregations