事件总线

一.总线配置
@Configuration
public class EventBusConfig {

    @Autowired
    private AsyncEventBusListener asyncEventBusListener;

    @Bean(name = "asyncEventBus")
    public EventBus asyncEventBus() {
        EventBus eventBus = new AsyncEventBus(
                new ThreadPoolExecutor(5, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(),
                        new ThreadFactoryBuilder().setDaemon(false).setNameFormat("eventbus-thread-%d").build()));
        eventBus.register(asyncEventBusListener);
        return eventBus;
    }
}

二.监听器

@Component
public class AsyncEventBusListener {
    /**
     * 每次提交数量
     */
    private static final int commitCount=10000;

    private final Retryer retry;

    /**
     * retryIf 重试条件可以多个
     * retryIfException 有异常重试
     * retryIfResult 判断返回结果是否重试
     * fixedWait 重试间隔
     * stopAfterAttempt 重试次数
     */
    public AsyncEventBusListener() {
        retry = RetryerBuilder.newBuilder().retryIfException().retryIfResult(Predicates.equalTo(false))
                 //配置等待策略                  七种等待策略
                .withWaitStrategy(WaitStrategies.fixedWait(500, TimeUnit.MILLISECONDS))
                 //配置终止策略                  三种终止策略
                .withStopStrategy(StopStrategies.stopAfterAttempt(5)).build();
    }


    @Subscribe
    public void testEvent(TestEvent testEvent) {
        //TODO 要处理的逻辑
        Callable undoCall = () -> {
            //要处理的业务逻辑,返回boolean类型,可以按返回的结果判断是否需要重试
            log.info("testEvent 消费异步消息 testEvent:{}", testEvent);
            return true;
            //return false
        };
        try {
            //真正调用
            retry.call(undoCall);
        } catch (RetryException e) {
            log.error("已达到指定重试次数均失败", e);
        } catch (ExecutionException e) {
            //https://blog.csdn.net/aitangyong/article/details/53894997
            log.error("流程异常、未指定的异常", e);
        }
    }

        //其他事件监听处理逻辑

}

七种等待策略:

ExceptionWaitStrategy
CompositeWaitStrategy
FibonacciWaitStrategy
ExponentialWaitStrategy
IncrementingWaitStrategy
RandomWaitStrategy
FixedWaitStrategy

三种终止策略:

StopAfterDelayStrategy
StopAfterAttemptStrategy
NeverStopStrategy

三.定义事件

@Data
@ToString
public class TestEvent {
    private Long id;
    private String name;
}

四.发布事件

业务层注入
@Autowired
private EventBus asyncEventBus;
业务方法中设置触发点:
Event event = new TestEvent();
event .setId(uuid());
asyncEventBus.post(insertTaskDetailEvent);

你可能感兴趣的:(JAVA,java,spring)