美文网首页
EventBusDemo

EventBusDemo

作者: LoWang | 来源:发表于2019-12-13 16:24 被阅读0次
    package com.scio.hanlin.crm;
    
    import java.util.UUID;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.LinkedBlockingDeque;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    import org.springframework.transaction.support.TransactionSynchronization;
    import org.springframework.transaction.support.TransactionSynchronizationManager;
    
    import com.google.common.eventbus.AsyncEventBus;
    import com.google.common.eventbus.EventBus;
    import com.google.common.eventbus.Subscribe;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.extern.slf4j.Slf4j;
    
    @Slf4j
    public class EventBusDemo {
    
        static ExecutorService executor =
            new ThreadPoolExecutor(2, 4, 60L, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(30));
        static EventBus bus = new AsyncEventBus(executor);
    
        public static void main(String[] args) throws InterruptedException {
            bus.register(new MyEventLisenter());
            // bus.register(new MyEventLisenter());
            log.info("post start");
            bus.post(new MyEvent(UUID.randomUUID().toString()));
            bus.post(new MyEvent(UUID.randomUUID().toString()));
            TimeUnit.SECONDS.sleep(2);
            log.info("post end");
            executor.shutdown();
            final int status = TransactionSynchronization.STATUS_COMMITTED;
    
        }
    
        public void publishAfterCommit(MyEvent event) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    bus.post(new MyEvent(UUID.randomUUID().toString()));
                };
            });
        }
    
        @Data
        @AllArgsConstructor
        public static class MyEvent {
            String id;
    
        }
    
        @Slf4j
        public static class MyEventLisenter {
    
            @Subscribe
            public void onEvent(MyEvent event) {
                log.info("onEvent : {}", event.getId());
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:EventBusDemo

          本文链接:https://www.haomeiwen.com/subject/qkofnctx.html