Java事件驱动编程

mtain 2022年09月26日 84次浏览

说明

事件监听(也叫事件驱动)是观察者模式的一种实现,只要是观察者模式,就含有主题(针对该主题的事件),发布者(发布主题或事件),订阅者(监听主题的人)。有三个部分组成,事件(ApplicationEvent)、监听器(ApplicationListener)和事件发布操作。

image-1664185728835

使用事件机制我们可以将相互耦合的代码解耦,从而方便功能拓展和调整。

参考文章:https://spring.jverson.com/other/spring-events.html

1. Spring Event

  1. 定义事件
/**
* 自定义的事件类
*/
@Getter
@Setter
public class CustomEvent extends ApplicationEvent {
 
    private String message;
 
    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public CustomEvent(Object source, String message) {
        super(source);
        this.message = message;
    }
 
}
  1. 定义事件发布
/**
* 事件发布类
*/
@Component
public class CustomEventPublish {
 
    @Autowired
    private ApplicationEventPublisher eventPublisher;
 
    public void publish(String message){
        CustomEvent event = new CustomEvent(this, message);
        eventPublisher.publishEvent(event);
    }
 
}
  1. 定义事件监听
/**
* 事件监听类
*/
@Component
public class CustomEventListener implements ApplicationListener<CustomEvent> {
    @Override
    public void onApplicationEvent(CustomEvent event) {
        System.out.println("get msg:"+ event.getMessage());
    }
}

或者使用注解

@Component
public class LightEventAnnotationListener {
    private static final Logger log = LoggerFactory.getLogger(LightEventAnnotationListener.class);
    @EventListener
    @Async  //异步方法
    public void handler(LightEvent event){
        try {
            Thread.sleep(2000); //模拟一个比较耗时的操作
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("traffic light:" + event.getLightColor().getMessage());
        log.info(Thread.currentThread().getName()); 
    }
}
  1. 执行事件发布
/**
* 测试类
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringeventApplicationTests {
 
    @Autowired
    private CustomEventPublish eventPublish;
 
    @Test
     public void test() {
        eventPublish.publish("hello");
    }
 
}
  1. 设置异步多线程执行
@Configuration
public class EventAsyncConfig {
    @Bean
    public SimpleAsyncTaskExecutor simpleAsyncTaskExecutor() {
        return new SimpleAsyncTaskExecutor();
    }
 
    @Bean
    public SimpleApplicationEventMulticaster applicationEventMulticaster() {
        SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = new SimpleApplicationEventMulticaster();
        simpleApplicationEventMulticaster.setTaskExecutor(simpleAsyncTaskExecutor());
        return simpleApplicationEventMulticaster;
    }
}

2. Google Guava EventBus(事件总线)

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>19.0</version>
</dependency>

3.SpringCloud Bus