使用异步提取

时间:2019-03-28 11:03:06

标签: java multithreading asynchronous google-cloud-pubsub

借助此link,我设法创建了一个小型Java应用程序,该应用程序将发布的消息拉一分钟。我的实现看起来像这样。

    public static void eventListener() throws InterruptedException {

    MessageReceiver receiver = new MessageReceiver() {
      @Override
      public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
        System.out.println("Received message: " + message.getData().toStringUtf8());
        consumer.ack();
      }
    };
    //Subscriber subscriber = null;
    try {
      subscriber = Subscriber.newBuilder(subscription, receiver)
          .setCredentialsProvider(FixedCredentialsProvider.create(creds)).build();
      subscriber.addListener(new Subscriber.Listener() {
        @Override
        public void failed(Subscriber.State from, Throwable failure) {
          // Handle failure. This is called when the Subscriber encountered a fatal error
          // and is
          // shutting down.
          System.err.println(failure);
        }
      }, MoreExecutors.directExecutor());
      subscriber.startAsync().awaitRunning();

      // In this example, we will pull messages for one minute (60,000ms) then stop.
      // In a real application, this sleep-then-stop is not necessary.
      // Simply call stopAsync().awaitTerminated() when the server is shutting down,
      // etc.
      Thread.sleep(60000);
    } finally {
      if (subscriber != null) {
        subscriber.stopAsync().awaitTerminated();
      }
    }
  }

当我在main

中调用此方法时
public static void main(String[] args) throws InterruptedException {
  eventListener();

}

并将对象上传到我的Google云存储中,该程序会打印出发布者发送的消息,例如

Received message: {
  "kind": "storage#object",
  "id": "roshanbucket/stones.jpg/1553765105996166",
  "selfLink": "https://www.googleapis.com/storage/v1/b/roshanbucket/o/stones.jpg",
  "name": "stones.jpg",
  "bucket": "roshanbucket",
  "generation": "1553765105996166",
  "metageneration": "1",
  "contentType": "image/jpeg",
  "timeCreated": "2019-03-28T09:25:05.995Z",
  "updated": "2019-03-28T09:25:05.995Z",
  "storageClass": "STANDARD",
  "timeStorageClassUpdated": "2019-03-28T09:25:05.995Z",
  "size": "137256",
  "md5Hash": "1GmpUnGeiW+/KU+0U8c8Wg==",
  "mediaLink": "https://www.googleapis.com/download/storage/v1/b/roshanbucket/o/stones.jpg?generation=1553765105996166&alt=media",
  "crc32c": "FMaEGg==",
  "etag": "CIaj1InCpOECEAE="
}

自程序执行以来的一分钟内,它会打印对象上传帐户中收到的所有消息,然后停止。要在一分钟后接收事件消息,我需要重新启动应用程序。现在,我要做的是连续运行侦听器,因此,我尝试在主方法内部的无限循环内运行方法eventListener(),例如

    public static void main(String[] args) throws InterruptedException {
    while(true) {
      eventListener();
    }
  }

有了这个,我似乎能够在每次上传后立即接收事件消息,而不管我何时上传对象。但是随后,它偶尔会抛出此堆栈跟踪。

    Mar 28, 2019 12:56:34 PM io.grpc.internal.ManagedChannelOrphanWrapper$ManagedChannelReference cleanQueue
SEVERE: *~*~*~ Channel ManagedChannelImpl{logId=6, target=pubsub.googleapis.com:443} was not shutdown properly!!! ~*~*~*
    Make sure to call shutdown()/shutdownNow() and wait until awaitTermination() returns true.
java.lang.RuntimeException: ManagedChannel allocation site
    at io.grpc.internal.ManagedChannelOrphanWrapper$ManagedChannelReference.<init>(ManagedChannelOrphanWrapper.java:103)
    at io.grpc.internal.ManagedChannelOrphanWrapper.<init>(ManagedChannelOrphanWrapper.java:53)
    at io.grpc.internal.ManagedChannelOrphanWrapper.<init>(ManagedChannelOrphanWrapper.java:44)
    at io.grpc.internal.AbstractManagedChannelImplBuilder.build(AbstractManagedChannelImplBuilder.java:440)
    at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.createSingleChannel(InstantiatingGrpcChannelProvider.java:223)
    at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.createChannel(InstantiatingGrpcChannelProvider.java:164)
    at com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.getTransportChannel(InstantiatingGrpcChannelProvider.java:156)
    at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:157)
    at com.google.cloud.pubsub.v1.stub.GrpcSubscriberStub.create(GrpcSubscriberStub.java:260)
    at com.google.cloud.pubsub.v1.Subscriber.doStart(Subscriber.java:268)
    at com.google.api.core.AbstractApiService$InnerService.doStart(AbstractApiService.java:148)
    at com.google.common.util.concurrent.AbstractService.startAsync(AbstractService.java:225)
    at com.google.api.core.AbstractApiService.startAsync(AbstractApiService.java:120)
    at com.google.cloud.pubsub.v1.Subscriber.startAsync(Subscriber.java:260)
    at listener.AsynchronousPull.eventListener(AsynchronousPull.java:57)
    at listener.AsynchronousPull.main(AsynchronousPull.java:74)

但是,它仍然在每次上传后打印消息,同时不时地抛出堆栈跟踪。我对thread的使用经验不足,非常感谢您为解决此问题提供的帮助。

1 个答案:

答案 0 :(得分:1)

在此处紧密调用eventListener()并不是您想要的。这将创建一个订阅者的许多新实例,这些实例分别接收60秒的消息。您想要的是使创建的订阅者的单个实例一直存在,直到您要关闭它为止。通常,您可以通过创建订户并通过awaitTerminated()等待订户来完成此操作。

上面的代码将被更改为这样:

public static void eventListener() throws InterruptedException {
  MessageReceiver receiver = new MessageReceiver() {
    @Override
    public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
      System.out.println("Received message: " + message.getData().toStringUtf8());
      consumer.ack();
    }
  };
  Subscriber subscriber = null;
  try {
    subscriber = Subscriber.newBuilder(subscription, receiver)
        .setCredentialsProvider(FixedCredentialsProvider.create(creds)).build();
    subscriber.addListener(new Subscriber.Listener() {
      @Override
      public void failed(Subscriber.State from, Throwable failure) {
        // Handle failure. This is called when the Subscriber encountered a fatal error
        // and is
        // shutting down.
        System.err.println(failure);
      }
    }, MoreExecutors.directExecutor());
    subscriber.startAsync().awaitRunning();
    subscriber.awaitTerminated();
  } finally {
    if (subscriber != null) {
      subscriber.stopAsync().awaitTerminated();
    }
  }
}

public static void main(String[] args) throws InterruptedException {
  eventListener();
}

如果您只希望订阅者在应用程序终止时停止并且不想打扰任何其他清理工作,那么上面的代码将起作用,允许订阅者运行并接收消息,直到发生错误或应用程序被删除为止。关掉。如果要在应用程序的干净终止上进行一些清理,例如,要确保已由receiveMessage处理的所有消息都运行到完成,则可以attach a shutdown hook捕获此类终止(尽管它不会在所有情况下都运行)。在此挂钩中,您将调用stopAsync()。例如,您可以在try块之前插入以下内容:

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
      subscriber.stopAsync().awaitTerminated();
    }
});