在单独的线程上重试

retry on separate thread

我正在尝试重新处理一些第一次失败的任务。我不想使用可完成的未来,因为它会打开新的线程和会话,所以当我们遇到很多失败时,它对我来说似乎无法扩展。

我正在使用 dropwizard,在我的服务开始时,我将队列传递给 Main class 和消费者。因为,我认为主 class 是 运行 在一个单独的线程上,我认为我不需要再次重新创建生产者 class [不确定]。

@Override
  public void run(PpsConfiguration configuration, Environment environment) {
    final BlockingQueue<Object[]> queue  = new LinkedBlockingQueue<>();

    new Thread(new Consumer(
         queue)).start(); //consumer at start of service
    
    environment.jersey().register(new MainClass(
            queue));

Consumer.java

public class Consumer extends MainClass implements Runnable {
  private final BlockingQueue<Object[]> queue;

  public Consumer(BlockingQueue<Object[]> queue) {
    super(queue);
    this.queue = queue;
  }

  @Override
  public void run() {

    try {
      while (true) {
        Object[] take = queue.take();
        someFunction(take);

      }
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }

}

MainClass.java 这是之前处理所有内容的主要 class。我只是展示 someFunction.

的定义

让我们假设前端正在触发这个函数并且是入口点。

private int mainFunction(Object[] take) {

    if (process(take)) {
        return 1;
      } else {
        // putting into queue
        queue.add(take); //producer thread adding
      }
    }
    return 0;
    }

public int someFunction(Object[] take) {
    int val = 0;
    for (int i=0;i<10; i++){ // retry 10 times until it succeeds
      LOGGER.info("retry # {}", i+1);
      val = process(take);
      if(val == 1){
        break;
      }
    }
    return val;
  }

(1) 我的理解是否正确,即我不需要单独创建 producer.java 来将任务添加到 queue。 (2) 如何以及在哪里可以 return 验证值? (3) 有没有办法像使用时间戳一样在 n 秒后重试特定类型的任务?

do not want to use completable future as it will open new threads and sessions so it doesn't seem scalable to me when we have lot of failures.

我认为对于 corner\error 案例,您不应该修改或必须修改几乎整个组件的结构。 dropwizard 确实提供了两个入口附加入口点,您可以使用它们来处理这种情况:

  1. 健康检查:https://www.dropwizard.io/en/latest/manual/core.html#health-checks
  2. 异常:https://www.dropwizard.io/en/latest/manual/core.html#error-handling

我更喜欢#1。

关于您的问题:

(1) Is my understanding correct i.e. I do not need to create a producer.java separately to add the tasks to queue.

是的,但见下文。

(2) How and where can I return the val?

当您 delay\retry 任务时,似乎没有办法 return 发送给发件人。您需要在链(注册)中插入 class 处理重试。但我不认为这会(很容易)成为可能。

(3) Is there a way to retry a specific type of task after n seconds like using timestamp?

我认为您应该通过创建自己的配置来适应这一点 (https://www.dropwizard.io/en/latest/manual/core.html#configuration);可能代表多个任务类型的多个配置 classes。