当前位置: 首页>>代码示例>>Java>>正文


Java PubsubMessage类代码示例

本文整理汇总了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("/");
}
 
开发者ID:GoogleCloudPlatform,项目名称:getting-started-java,代码行数:25,代码来源:PubSubPublish.java

示例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();
	}
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:27,代码来源:PubSubInboundChannelAdapter.java

示例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();
}
 
开发者ID:GoogleCloudPlatform,项目名称:pubsub,代码行数:9,代码来源:CPSSubscriberTask.java

示例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());
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:25,代码来源:PubSubPublish.java

示例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));
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:17,代码来源:PubSubPublishTest.java

示例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();
    }
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:24,代码来源:SubscriberExample.java

示例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());
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:25,代码来源:PubSubPublish.java

示例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()));
  }
}
 
开发者ID:streamsets,项目名称:datacollector,代码行数:19,代码来源:MessageProcessorImpl.java

示例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));
}
 
开发者ID:streamsets,项目名称:datacollector,代码行数:21,代码来源:PubSubTarget.java

示例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());
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:12,代码来源:PubSubTemplate.java

示例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);
	}
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:42,代码来源:PubSubTemplate.java

示例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();
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:19,代码来源:PubSubTemplateTests.java

示例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));
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:8,代码来源:PubSubTemplateTests.java

示例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));
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:8,代码来源:PubSubTemplateTests.java

示例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);
    }
}
 
开发者ID:RapturePlatform,项目名称:Rapture,代码行数:31,代码来源:PubsubPipeline2Handler.java


注:本文中的com.google.pubsub.v1.PubsubMessage类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。