本文整理汇总了Java中com.google.pubsub.v1.PubsubMessage类的典型用法代码示例。如果您正苦于以下问题:Java PubsubMessage类的具体用法?Java PubsubMessage怎么用?Java PubsubMessage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
PubsubMessage类属于com.google.pubsub.v1包,在下文中一共展示了PubsubMessage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doPost
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Publisher publisher = this.publisher;
// construct a pubsub message from the payload
final String payload = req.getParameter("payload");
Message message = new Message(null);
message.setData(payload);
PubsubMessage pubsubMessage =
PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(payload))
.putAttributes("sourceLang", req.getParameter("sourceLang"))
.putAttributes("targetLang", req.getParameter("targetLang"))
.build();
String topicId = System.getenv("PUBSUB_TOPIC");
// create a publisher on the topic
if (publisher == null) {
this.publisher = publisher = Publisher.newBuilder(
TopicName.of(ServiceOptions.getDefaultProjectId(), topicId))
.build();
}
publisher.publish(pubsubMessage);
// redirect to home page
resp.sendRedirect("/");
}
示例2: receiveMessage
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
private void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
Map<String, Object> messageHeaders = new HashMap<>();
message.getAttributesMap().forEach(messageHeaders::put);
if (this.ackMode == AckMode.MANUAL) {
// Send the consumer downstream so user decides on when to ack/nack.
messageHeaders.put(GcpHeaders.ACKNOWLEDGEMENT, consumer);
}
try {
sendMessage(this.messageConverter.toMessage(
message.getData().toStringUtf8(),
new MessageHeaders(messageHeaders)));
}
catch (RuntimeException re) {
if (this.ackMode == AckMode.AUTO) {
consumer.nack();
}
throw re;
}
if (this.ackMode == AckMode.AUTO) {
consumer.ack();
}
}
示例3: receiveMessage
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
@Override
public void receiveMessage(final PubsubMessage message, final AckReplyConsumer consumer) {
recordMessageLatency(
Integer.parseInt(message.getAttributesMap().get("clientId")),
Integer.parseInt(message.getAttributesMap().get("sequenceNumber")),
System.currentTimeMillis() - Long.parseLong(message.getAttributesMap().get("sendTime")));
consumer.ack();
}
示例4: doPost
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
Publisher publisher = this.publisher;
try {
String topicId = System.getenv("PUBSUB_TOPIC");
// create a publisher on the topic
if (publisher == null) {
publisher = Publisher.newBuilder(
TopicName.of(ServiceOptions.getDefaultProjectId(), topicId))
.build();
}
// construct a pubsub message from the payload
final String payload = req.getParameter("payload");
PubsubMessage pubsubMessage =
PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(payload)).build();
publisher.publish(pubsubMessage);
// redirect to home page
resp.sendRedirect("/");
} catch (Exception e) {
resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
}
示例5: servletPublishesPayloadMessage
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
@Test
public void servletPublishesPayloadMessage() throws Exception {
assertNotNull(System.getenv("PUBSUB_TOPIC"));
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getParameter("payload")).thenReturn("test-message");
HttpServletResponse response = mock(HttpServletResponse.class);
Publisher publisher = mock(Publisher.class);
PubsubMessage message = PubsubMessage.newBuilder()
.setData(ByteString.copyFromUtf8("test-message")).build();
when(publisher.publish(eq(message))).thenReturn(SettableApiFuture.create());
PubSubPublish pubSubPublish = new PubSubPublish(publisher);
// verify content of published test message
pubSubPublish.doPost(request, response);
verify(publisher, times(1)).publish(eq(message));
}
示例6: main
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
/** Receive messages over a subscription. */
public static void main(String... args) throws Exception {
// set subscriber id, eg. my-sub
String subscriptionId = args[0];
SubscriptionName subscriptionName = SubscriptionName.of(PROJECT_ID, subscriptionId);
Subscriber subscriber = null;
try {
// create a subscriber bound to the asynchronous message receiver
subscriber =
Subscriber.newBuilder(subscriptionName, new MessageReceiverExample()).build();
subscriber.startAsync().awaitRunning();
// Continue to listen to messages
while (true) {
PubsubMessage message = messages.take();
System.out.println("Message Id: " + message.getMessageId());
System.out.println("Data: " + message.getData().toStringUtf8());
}
} finally {
if (subscriber != null) {
subscriber.stopAsync();
}
}
}
示例7: doPost
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
Publisher publisher = this.publisher;
try {
String topicId = System.getenv("PUBSUB_TOPIC");
// create a publisher on the topic
if (publisher == null) {
publisher = Publisher.defaultBuilder(
TopicName.create(ServiceOptions.getDefaultProjectId(), topicId))
.build();
}
// construct a pubsub message from the payload
final String payload = req.getParameter("payload");
PubsubMessage pubsubMessage =
PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(payload)).build();
publisher.publish(pubsubMessage);
// redirect to home page
resp.sendRedirect("/");
} catch (Exception e) {
resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
}
示例8: parseMessage
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
private void parseMessage(PubsubMessage message) {
LOG.trace("parseMessage called");
try (DataParser parser = parserFactory.getParser(message.getMessageId(), message.getData().toByteArray())) {
Record r;
while ((r = tryParse(parser, message)) != null) {
setHeaders(message, r);
batchMaker.addRecord(r);
++currentRecordCount;
}
} catch (DataParserException | IOException e) {
LOG.error(Errors.PUBSUB_05.getMessage(), e.toString(), e);
// Create a raw record of the gRPC message data, set attributes as headers, and use the messageId for the recordId
Record errorRecord = context.createRecord(message.getMessageId(), message.getData().toByteArray(), MIME_GRPC);
setHeaders(message, errorRecord);
context.reportError(new OnRecordErrorException(errorRecord, Errors.PUBSUB_05, e.toString()));
}
}
示例9: publish
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
private void publish(Record record) throws StageException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try (DataGenerator generator = generatorFactory.getGenerator(os)) {
generator.write(record);
} catch (IOException | DataGeneratorException e) {
errorRecordHandler.onError(new OnRecordErrorException(record, Errors.PUBSUB_06, e.toString(), e));
return;
}
ByteString data = ByteString.copyFrom(os.toByteArray());
Map<String, String> attributes = new HashMap<>();
Record.Header header = record.getHeader();
header.getAttributeNames().forEach(k -> attributes.put(k, header.getAttribute(k)));
PubsubMessage message = PubsubMessage.newBuilder().setData(data).putAllAttributes(attributes).build();
ApiFuture<String> messageIdFuture = publisher.publish(message);
pendingMessages.add(new PendingMessage(record, messageIdFuture));
}
示例10: publish
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
@Override
public ListenableFuture<String> publish(final String topic, ByteString payload,
Map<String, String> headers) {
PubsubMessage.Builder pubsubMessageBuilder = PubsubMessage.newBuilder().setData(payload);
if (headers != null) {
pubsubMessageBuilder.putAllAttributes(headers);
}
return publish(topic, pubsubMessageBuilder.build());
}
示例11: pull
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
/**
* Pulls messages synchronously, on demand, using the pull request in argument.
*
* <p>
* This method acknowledges all received messages.
* @param pullRequest pull request containing the subscription name
* @return the list of {@link PubsubMessage} containing the headers and payload
*/
private List<PubsubMessage> pull(PullRequest pullRequest, RetrySettings retrySettings) {
Assert.notNull(pullRequest, "The pull request cannot be null.");
try {
SubscriberStub subscriber = this.subscriberFactory.createSubscriberStub(retrySettings);
Assert.notNull(subscriber, "A SubscriberStub is needed to execute the pull request.");
PullResponse pullResponse = subscriber.pullCallable().call(pullRequest);
// Ack received messages.
if (pullResponse.getReceivedMessagesCount() > 0) {
List<String> ackIds = pullResponse.getReceivedMessagesList().stream()
.map(ReceivedMessage::getAckId)
.collect(Collectors.toList());
AcknowledgeRequest acknowledgeRequest = AcknowledgeRequest.newBuilder()
.setSubscriptionWithSubscriptionName(
pullRequest.getSubscriptionAsSubscriptionName())
.addAllAckIds(ackIds)
.build();
subscriber.acknowledgeCallable().call(acknowledgeRequest);
}
return pullResponse.getReceivedMessagesList().stream()
.map(ReceivedMessage::getMessage)
.collect(Collectors.toList());
}
catch (Exception ioe) {
throw new PubSubException("Error pulling messages from subscription "
+ pullRequest.getSubscription() + ".", ioe);
}
}
示例12: setUp
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
@Before
public void setUp() {
this.pubSubTemplate = new PubSubTemplate(this.mockPublisherFactory,
this.mockSubscriberFactory);
when(this.mockPublisherFactory.createPublisher("testTopic"))
.thenReturn(this.mockPublisher);
this.settableApiFuture = SettableApiFuture.create();
when(this.mockPublisher.publish(isA(PubsubMessage.class)))
.thenReturn(this.settableApiFuture);
when(this.mockSubscriberFactory.createSubscriber(
eq("testSubscription"), isA(MessageReceiver.class)))
.thenReturn(this.mockSubscriber);
when(this.mockSubscriber.startAsync()).thenReturn(mock(ApiService.class));
this.pubsubMessage = PubsubMessage.newBuilder().setData(
ByteString.copyFrom("permanating".getBytes())).build();
}
示例13: testPublish_String
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
@Test
public void testPublish_String() {
this.pubSubTemplate.publish("testTopic", "testPayload", null);
verify(this.mockPublisher, times(1))
.publish(isA(PubsubMessage.class));
}
示例14: testPublish_Bytes
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
@Test
public void testPublish_Bytes() {
this.pubSubTemplate.publish("testTopic", "testPayload".getBytes(), null);
verify(this.mockPublisher, times(1))
.publish(isA(PubsubMessage.class));
}
示例15: publishTask
import com.google.pubsub.v1.PubsubMessage; //导入依赖的package包/类
@Override
public void publishTask(final String queue, final String task) {
Topic topic = getTopic(queue);
ByteString data = ByteString.copyFromUtf8(task);
TopicName topicName = topic.getNameAsTopicName();
try {
PubsubMessage psmessage = PubsubMessage.newBuilder().setData(data).build();
Publisher publisher = randomHouse.get(topicName);
if (publisher == null) {
logger.trace("No publisher found for " + topicName + " - creating");
Builder builder = Publisher.defaultBuilder(topicName);
// The default executor provider creates an insane number of threads.
if (executor != null) builder.setExecutorProvider(executor);
publisher = builder.build();
randomHouse.put(topicName, publisher);
} else {
logger.trace("Existing publisher found for " + topicName);
}
ApiFuture<String> messageIdFuture = publisher.publish(psmessage);
if (executor != null) messageIdFuture.addListener(listener, executor.getExecutor());
} catch (IOException e) {
String error = String.format("Cannot send message to topic %s:\n%s", topic.getName(), ExceptionToString.format(e));
logger.error(error);
throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, error, e);
}
}