当前位置: 代码迷 >> 综合 >> 记录学习,spring + Guava EventBus
  详细解决方案

记录学习,spring + Guava EventBus

热度:71   发布时间:2024-02-21 18:05:04.0
@Component
public class ConsumerEvent001 implements EventAbstract<TestEvent001> {
    @Subscribe@Overridepublic void handle(TestEvent001 event) {
    System.out.println("处理代码001:" + event.getName() + "------------------");}
}@Component
public class ConsumerEvent002 implements  EventAbstract<TestEvent002>{
    @Subscribe@Overridepublic void handle(TestEvent002 event) {
    //ThreadUtil.sleep(3000);System.out.println("处理代码002:" + event.getName()+ "---------------------");}
}/*** Event 事件处理抽象接口类* @author zhangxun*/
public interface EventAbstract<E> {
    /*** event* @param event*/void handle(E event);
}/*** @Author: ZX* @Date: */@Configuration
public class EventConfig {
    @Beanpublic EventBus eventBus(){
    EventBus eventBus = new EventBus();return eventBus;}@Beanpublic AsyncEventBus asyncEventBus(){
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3 , 10 , 3000L , TimeUnit.SECONDS,  new ArrayBlockingQueue<>(3));return new AsyncEventBus(threadPoolExecutor);}}/*** @Author: ZX* @Date: */@Component
public class EventListenerRegist {
    @Autowiredprivate EventBus eventBus;// @Qualifier(value = "asyncEventBus")
// @Autowired
// private AsyncEventBus asyncEventBus;@Autowiredprivate ConsumerEvent001 consumerEvent001;@Autowiredprivate ConsumerEvent002 consumerEvent002;@PostConstructpublic void init(){
    eventBus.register(consumerEvent001);eventBus.register(consumerEvent002);}}@Component
public class ProviderEvent {
    @Autowiredprivate EventBus eventBus;@Autowiredprivate AsyncEventBus asyncEventBus;public <T> void  post(T t){
    eventBus.post(t);}public <T> void   asyncPost(T t){
    eventBus.post(t);}
}public class TestEvent001 {
    }public class TestEvent002 {
    }public class TestApp {
    public static void main(String[] args) {
    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(TestApp.class);annotationConfigApplicationContext.scan("com");TestEvent001 testEvent001 = new TestEvent001("test001");ProviderEvent bean =   annotationConfigApplicationContext.getBean(ProviderEvent.class);for(int i = 0 ;i < 100 ; i++){
    bean.asyncPost(new TestEvent002("test002--" + i));}//bean.post(testEvent001);}}
  相关解决方案