spring-rabbitmq 和线程本地 - 什么时候是调用 clean 方法的好时机

spring-rabitmq and thread local - when is a good moment to invoke clean method

我有一个 @RabbitListener 并且可以正常使用队列中的内容。 在我的听众中,我设置了上下文。

我知道有许多(可配置的)线程使用同一个队列(所以实际上执行相同的监听器代码)。

现在,我想什么时候是清除上下文的好时机?

更准确地说,我要表达的是问题:

"When you end consuming (no matter with exception or not) do clear context)"

下面,你可以看到我的问题的方案:

public class CustomContextHolder {

   private static final ThreadLocal<DatabaseType> contextHolder = 
            new ThreadLocal<DatabaseType>();

   public static void setContext(DatabaseType databaseType) {
      contextHolder.set(databaseType);
   }

   public static CustomerType getContext() {
      return (CustomerType) contextHolder.get();
   }

   public static void clearContext() {
      contextHolder.remove();
   }
}


@RabbitListener
void listenMessage(Message message) {
  ...
  CustomContextHolder.set(...);

}

通常使用无状态对象作为侦听器比使用 ThreadLocal 更好。

但是,如果您被迫以这种方式保持状态,则可以实现 ApplicationListener<AmqpEvent>

ApplicationListener会收到几个事件;具体来说,消费者正常停止时的 AsyncConsumerStoppedEvent 和消费者异常停止时的 ListenerContainerConsumerFailedEvent 。这两个事件发布在侦听器线程上,因此您可以在那里清除您的ThreadLocal

其他事件可能会也可能不会发布在侦听器线程上。