8.12.3. 使用 Jakarta Interceptors 刷新 Jakarta Enterprise Beans-clustered timers

您可以通过对业务方法配置 Jakarta Interceptors 以编程方式刷新计时器,从而强制计时器在 刷新过期前进行 刷新。

注意

在集群部署中,如果多个节点在较短的时间内更新其数据存储,内存中计时器状态可能会临时变得不同步。

先决条件

  • 您已配置了数据库支持的集群 Jakarta Enterprise Beans。

流程

  1. 实施 Jakarta Interceptors,使 wildfly.ejb.timer.refresh.enabled 设为 true

    import javax.interceptor.AroundInvoke;
    import javax.interceptor.Interceptor;
    import javax.interceptor.InvocationContext;
    
    /**
     * An interceptor to enable programmatic timer refresh across multiple nodes.
     */
    @Interceptor
    public class RefreshInterceptor {
        @AroundInvoke
        public Object intercept(InvocationContext context) throws Exception {
            context.getContextData().put("wildfly.ejb.timer.refresh.enabled", Boolean.TRUE);
            return context.proceed();
        }
    }
  2. 配置 Jakarta Interceptors。

    • 您可以将 Jakarta Interceptors 配置为目标无状态或单例 bean 商业方法。当 wildfly.ejb.timer.refresh.enabled 设为 true 时,调用 TimerService.getAllTimers() 会在返回计时器前刷新计时器数据存储。

      @Singleton
      public class RefreshBean1 ... {
      
          @Interceptors(RefreshInterceptor.class)
          public void businessMethod1() {
              ...
              // since wildfly.ejb.timer.refresh.enabled is set to true in interceptor for this business method,
              // calling timerService.getAllTimers() will first refresh from timer datastore before returning timers.
              final Collection<Timer> allTimers = timerService.getAllTimers();
              ...
          }
      }
    • 或者,您也可以实施一种专用的业务方法,以便在需要时以编程方式刷新应用的其他部分调用的计时器。

          @Interceptors(RefreshInterceptor.class)
          public List<Timer> getAllTimerInfoWithRefresh() {
              return timerService.getAllTimers();
          }
      
          public void businessMethod1() {
              final LocalBusinessInterface businessObject = sessionContext.getBusinessObject(LocalBusinessInterface.class);
              businessObject.getAllTimerInfoWithRefresh();
      
              // timer has been programmatically refreshed from datastore.
              // continue with other business logic...
          }