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


Java Publisher类代码示例

本文整理汇总了Java中com.google.cloud.pubsub.v1.Publisher的典型用法代码示例。如果您正苦于以下问题:Java Publisher类的具体用法?Java Publisher怎么用?Java Publisher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Publisher类属于com.google.cloud.pubsub.v1包,在下文中一共展示了Publisher类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: doPost

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的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: CPSPublisherTask

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的package包/类
private CPSPublisherTask(StartRequest request) {
  super(request, "gcloud", MetricsHandler.MetricName.PUBLISH_ACK_LATENCY);
  try {
    this.publisher =
        Publisher.defaultBuilder(TopicName.create(request.getProject(), request.getTopic()))
            .setBatchingSettings(
                BatchingSettings.newBuilder()
                    .setElementCountThreshold(950L)
                    .setRequestByteThreshold(9500000L)
                    .setDelayThreshold(
                        Duration.ofMillis(Durations.toMillis(request.getPublishBatchDuration())))
                    .build())
            .build();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  this.payload = ByteString.copyFromUtf8(LoadTestRunner.createMessage(request.getMessageSize()));
  this.batchSize = request.getPublishBatchSize();
  this.messageSize = request.getMessageSize();
  this.id = (new Random()).nextInt();
}
 
开发者ID:GoogleCloudPlatform,项目名称:pubsub,代码行数:22,代码来源:CPSPublisherTask.java

示例3: doPost

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的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

示例4: servletPublishesPayloadMessage

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的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

示例5: doPost

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的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

示例6: createPublisher

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的package包/类
@Override
public Publisher createPublisher(String topic) {
	return this.publishers.computeIfAbsent(topic, key -> {
		try {
			Publisher.Builder publisherBuilder =
					Publisher.newBuilder(TopicName.of(this.projectId, key));

			if (this.executorProvider != null) {
				publisherBuilder.setExecutorProvider(this.executorProvider);
			}

			if (this.channelProvider != null) {
				publisherBuilder.setChannelProvider(this.channelProvider);
			}

			if (this.credentialsProvider != null) {
				publisherBuilder.setCredentialsProvider(this.credentialsProvider);
			}

			if (this.retrySettings != null) {
				publisherBuilder.setRetrySettings(this.retrySettings);
			}

			if (this.batchingSettings != null) {
				publisherBuilder.setBatchingSettings(this.batchingSettings);
			}

			return publisherBuilder.build();
		}
		catch (IOException ioe) {
			throw new PubSubException("An error creating the Google Cloud Pub/Sub publisher " +
					"occurred.", ioe);
		}
	});
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:36,代码来源:DefaultPublisherFactory.java

示例7: testGetPublisher

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的package包/类
@Test
public void testGetPublisher() {
	DefaultPublisherFactory factory = new DefaultPublisherFactory(() -> "projectId");
	factory.setCredentialsProvider(this.credentialsProvider);
	Publisher publisher = factory.createPublisher("testTopic");

	assertEquals(factory.getCache().size(), 1);
	assertEquals(publisher, factory.getCache().get("testTopic"));
	assertEquals("testTopic", publisher.getTopicName().getTopic());
	assertEquals("projectId", publisher.getTopicName().getProject());
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:12,代码来源:DefaultPublisherFactoryTests.java

示例8: init

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的package包/类
@Override
protected List<ConfigIssue> init() {
  List<ConfigIssue> issues = super.init();

  pendingMessages.clear();
  errorRecordHandler = new DefaultErrorRecordHandler(getContext());

  if (conf.dataFormatConfig.init(
      getContext(),
      conf.dataFormat,
      Groups.DATA_FORMAT.name(),
      "conf.dataFormat.",
      issues
  )) {
    generatorFactory = conf.dataFormatConfig.getDataGeneratorFactory();
  }

  TopicName topic = TopicName.create(conf.credentials.projectId, conf.topicId);

  conf.credentials.getCredentialsProvider(getContext(), issues).ifPresent(p -> credentialsProvider = p);

  try {
    publisher = Publisher.defaultBuilder(topic).setCredentialsProvider(credentialsProvider).build();
  } catch (IOException e) {
    LOG.error(Errors.PUBSUB_07.getMessage(), conf.topicId, e.toString(), e);
    issues.add(getContext().createConfigIssue(
        Groups.PUBSUB.name(),
        "conf.topicId",
        Errors.PUBSUB_07,
        conf.topicId,
        e.toString()
    ));
  }

  return issues;
}
 
开发者ID:streamsets,项目名称:datacollector,代码行数:37,代码来源:PubSubTarget.java

示例9: getCache

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的package包/类
@VisibleForTesting
Map<String, Publisher> getCache() {
	return this.publishers;
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:5,代码来源:DefaultPublisherFactory.java

示例10: PubSubPublish

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的package包/类
PubSubPublish(Publisher publisher) {
  this.publisher = publisher;
}
 
开发者ID:GoogleCloudPlatform,项目名称:getting-started-java,代码行数:4,代码来源:PubSubPublish.java

示例11: main

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的package包/类
/** Publish messages to a topic.
 * @param args topic name, number of messages
 */
public static void main(String... args) throws Exception {
  // topic id, eg. "my-topic"
  String topicId = args[0];
  int messageCount = Integer.parseInt(args[1]);
  TopicName topicName = TopicName.of(PROJECT_ID, topicId);
  Publisher publisher = null;
  try {
    // Create a publisher instance with default settings bound to the topic
    publisher = Publisher.newBuilder(topicName).build();

    for (int i = 0; i < messageCount; i++) {
      String message = "message-" + 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);

      // add an asynchronous callback to handle success / failure
      ApiFutures.addCallback(future, new ApiFutureCallback<String>() {

        @Override
        public void onFailure(Throwable throwable) {
          if (throwable instanceof ApiException) {
            ApiException apiException = ((ApiException) throwable);
            // details on the API exception
            System.out.println(apiException.getStatusCode().getCode());
            System.out.println(apiException.isRetryable());
          }
          System.out.println("Error publishing message : " + message);
        }

        @Override
        public void onSuccess(String messageId) {
          // Once published, returns server-assigned message ids (unique within the topic)
          System.out.println(messageId);
        }
      });
    }
  } finally {
    if (publisher != null) {
      // When finished with the publisher, shutdown to free up resources.
      publisher.shutdown();
    }
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:54,代码来源:PublisherExample.java

示例12: createPublisher

import com.google.cloud.pubsub.v1.Publisher; //导入依赖的package包/类
Publisher createPublisher(String topic); 
开发者ID:spring-cloud,项目名称:spring-cloud-gcp,代码行数:2,代码来源:PublisherFactory.java


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