Guava之EventBus實戰

EventBus是Guava的事件處理機制,是設計模式中的觀察者模式(生產/消費者編程模型)的優雅實現。對於事件監聽和發佈訂閱模式,EventBus是一個非常優雅和簡單解決方案,我們不用創建複雜的類和接口層次結構。

定義EventBus

@Configuration
public class EventBusConfig {

    @Autowired
    private ApplicationContext context;

    /**
     * 功能描述: <br>
     * ConditionalOnMissingBean判斷是否執行初始化代碼,即如果用戶已經創建bean,則相關的初始化代碼不再執行
     */
    @Bean
    @ConditionalOnMissingBean(AsyncEventBus.class)
    AsyncEventBus createEventBus() {
        // 定義一個EventBus對象
        AsyncEventBus eventBus = new AsyncEventBus(Executors.newFixedThreadPool(5));
        Reflections reflections = new Reflections("com.google.guava.listener", new MethodAnnotationsScanner());
        Set<Method> methods = reflections.getMethodsAnnotatedWith(Subscribe.class);
        if (null != methods) {
            for (Method method : methods) {
                try {
                    System.out.println("註冊監聽器:" + context.getBean(method.getDeclaringClass()));
                    eventBus.register(context.getBean(method.getDeclaringClass()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return eventBus;
    }
}

定義Event

public interface IEvent {
    void print();
}

public class LoginEvent implements IEvent{
    @Override
    public void print() {
        System.out.println("login ......");
    }
}

public class LogoutEvent implements IEvent {
    @Override
    public void print() {
        System.out.println("logout ......");
    }
}

public class BusinessEvent implements IEvent{
    @Override
    public void print() {
        System.out.println("business ......");
    }
}

定義Listener

public interface IEventListener {
    void login(LoginEvent event);
    void business(BusinessEvent event);
    void logout(LogoutEvent event);
}

/**
 * 同一個監聽者可以監聽多種類型的事件
 */
@Component
public class LoginEventListener extends EventListenerAdapter {

    @Subscribe
    @Override
    public void login(LoginEvent event) {
        System.out.println("login receive event ...");
        event.print();
    }

    @Subscribe
    @Override
    public void business(BusinessEvent event) {
        System.out.println("business receive event ...");
        event.print();
    }
}

/**
 * 同一個監聽器多次監聽同一個事件
 */
@Component
public class LogoutEventListener extends EventListenerAdapter{

    @Subscribe
    @Override
    public void logout(LogoutEvent event) {
        System.out.println("logout receive event ...");
        event.print();
    }

    @Subscribe
    public void logoutT(LogoutEvent event) {
        System.out.println("logoutT receive event ...");
        event.print();
    }
}


public abstract class EventListenerAdapter implements IEventListener{

    @Override
    public void login(LoginEvent event) {
    }

    @Override
    public void business(BusinessEvent enent) {
    }

    @Override
    public void logout(LogoutEvent event) {
    }
}

定義事件發佈接口

public interface IBusinessService {
    void post(IEvent event);
}

@Service
public class BusinessServiceImpl implements IBusinessService {

    @Autowired
    private AsyncEventBus eventBus;

    @Override
    public void post(IEvent event) {
        if (null != event) {
            // 事件發佈
            eventBus.post(event);
        }
    }
}

啓動觸發事件

@Component
public class StartRunner implements CommandLineRunner {

    @Autowired
    private IBusinessService businessService;

    @Override
    public void run(String... args) throws Exception {
        IEvent loginEvent = new LoginEvent();
        businessService.post(loginEvent);
        IEvent logoutEvent = new LogoutEvent();
        businessService.post(logoutEvent);
        IEvent businessEvent = new BusinessEvent();
        businessService.post(businessEvent);
    }
}

啓動類

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class EventBusApplication {

    public static void main(String[] args) {
        try {
            SpringApplication.run(EventBusApplication.class, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

原理分析
https://www.jianshu.com/p/4bddd45a8e7a

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章