Guava(事件總線): 事件總線EventBus

EventBus:

建立EventBus實例:

EventBus eventBus = new EventBus();
//或者
EventBus eventBus = new EventBus(TradeAccountEvent.class.getName());//帶標識符,用於日誌記錄

訂閱事件:

  • 模擬一個交易過程。java

  • 事件類:框架

/**
 * 事件類
 */
public class TradeAccountEvent {
    private double amount;
    private Date tradeExecutionTime;
    private TradeType tradeType;
    private TradeAccount tradeAccount;
 
    public TradeAccountEvent(TradeAccount account, double amount,
            Date tradeExecutionTime, TradeType tradeType) {
        this.amount = amount;
        this.tradeExecutionTime = tradeExecutionTime;
        this.tradeAccount = account;
        this.tradeType = tradeType;
    }
}
 
/**
 * 購買事件
 */
public class BuyEvent extends TradeAccountEvent {
    public BuyEvent(TradeAccount tradeAccount, double amount,
            Date tradExecutionTime) {
        super(tradeAccount, amount, tradExecutionTime, TradeType.BUY);
    }
}
 
/**
 * 賣出事件
 */
public class SellEvent extends TradeAccountEvent {
    public SellEvent(TradeAccount tradeAccount, double amount,
            Date tradExecutionTime) {
        super(tradeAccount, amount, tradExecutionTime, TradeType.SELL);
    }
}
  • 訂閱者異步

/**
 * 賣出和購買審計,即訂閱者
 */
public class AllTradesAuditor {
    private List<BuyEvent> buyEvents = Lists.newArrayList();
    private List<SellEvent> sellEvents = Lists.newArrayList();
 
    public AllTradesAuditor(EventBus eventBus) {
        eventBus.register(this);
    }
 
    /**
     * 訂閱賣出事件
     */
    @Subscribe
    public void auditSell(SellEvent sellEvent) {
        sellEvents.add(sellEvent);
        System.out.println("Received TradeSellEvent " + sellEvent);
    }
 
    /**
     * 訂閱購買事件
     */
    @Subscribe
    public void auditBuy(BuyEvent buyEvent) {
        buyEvents.add(buyEvent);
        System.out.println("Received TradeBuyEvent " + buyEvent);
    }
}
  • 發佈者async

/**
 * 執行交易, 即發佈者
 */
public class SimpleTradeExecutor {
    private EventBus eventBus;
 
    public SimpleTradeExecutor(EventBus eventBus) {
        this.eventBus = eventBus;
    }
 
    /**
     * 執行交易
     */
    public void executeTrade(TradeAccount tradeAccount, double amount,
            TradeType tradeType) {
        TradeAccountEvent tradeAccountEvent = processTrade(tradeAccount,
                amount, tradeType);
        eventBus.post(tradeAccountEvent); // 發佈事件
    }
 
    /**
     * 處理交易
     * 
     * @return 交易事件
     */
    private TradeAccountEvent processTrade(TradeAccount tradeAccount,
            double amount, TradeType tradeType) {
        Date executionTime = new Date();
        String message = String.format(
                "Processed trade for %s of amount %n type %s @ %s",
                tradeAccount, amount, tradeType, executionTime);
        TradeAccountEvent tradeAccountEvent;
        if (tradeType.equals(TradeType.BUY)) { //購買動做
            tradeAccountEvent = new BuyEvent(tradeAccount, amount,
                    executionTime);
        } else { //賣出動做
            tradeAccountEvent = new SellEvent(tradeAccount, amount,
                    executionTime);
        }
        System.out.println(message);
        return tradeAccountEvent;
    }
}
  • 測試用例post

EventBus eventBus = new EventBus();
AllTradesAuditor auditor = new AllTradesAuditor(eventBus);
SimpleTradeExecutor tradeExecutor = new SimpleTradeExecutor(eventBus);
tradeExecutor.executeTrade(new TradeAccount(), 1000, TradeType.SELL);
tradeExecutor.executeTrade(new TradeAccount(), 2000, TradeType.BUY);

取消訂閱:

  • 訂閱者來取消註冊測試

public void unregister(){
      this.eventBus.unregister(this);
}

AsyncEventBus類

  • 聞其名,就是異步事件總線,當處理耗時的處理時頗有用,咱們要依賴Executors來實現異步事件總線ui

AsyncEventBus asyncEventBus = new AsyncEventBus(executorService);

DeadEvents:

  • 當總線接收到發佈者發佈的信息時,但這時沒有訂閱者,那麼該事件會被包裝爲DeadEvent事件this

public class DeadEventSubscriber {
    private static final Logger logger = 
            Logger.getLogger(DeadEventSubscriber.class.getName());
 
    public DeadEventSubscriber(EventBus eventBus) {
        eventBus.register(this);
    }
     
    /**
     * 沒有訂閱者時被觸發
     */
    @Subscribe
    public void handleUnsubscribedEvent(DeadEvent event){
        logger.warning("No subscribers for "+event.getEvent());
    }
}

依賴注入

  • 咱們能夠經過DI框架(Spring或Guice)來注入一樣的EventBusspa

@Component
public class SimpleTradeExecutor {
       private EventBus eventBus;
       @Autowired
       public SimpleTradeExecutor(EventBus eventBus) {
           this.eventBus = checkNotNull(eventBus, "EventBus can't be null");                                             }
}
@Component
public class SimpleTradeAuditor {
       private List<TradeAccountEvent> tradeEvents =
    Lists.newArrayList();
    @Autowired
    public SimpleTradeAuditor(EventBus eventBus){
           checkNotNull(eventBus,"EventBus can't be null");
           eventBus.register(this);
   }
}

以上就介紹了Guava的EventBus。日誌

相關文章
相關標籤/搜索