spring 使用事件驱动

概述:
一、三要素
1、监听器:Listener
2、事件源:event
3、事件的发布者:Publisher
二、实现方式
1、事件源:Event设计

// 重点是继承 ApplicationEvent
public class MyEvent extends ApplicationEvent {
    private static final long serialVersionUID = -6921924726678224331L;
    /**
     *  这里是一些事件的私有属性,比如name或者什么其他对象
     */
    private String name;

    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public MyEvent(Object source) {
        super(source);
        if(source instanceof String){
            name = source.toString();
        }
    }

    public String getName() {
        return name;
    }
}

2、监听器设计

@Component
public class MyListener implements ApplicationListener {
    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(MyEvent event) {
    	// 用于处理事件,也就是事件触发后的执行逻辑
        System.out.println("MyListener处理事件,获取事件属性数据:"+event.getName());
    }
}

3、事件的发布者设计

// 继承至SimpleApplicationEventMulticaster,可以用于发布事件
public class MyPublisher extends SimpleApplicationEventMulticaster{
	
	// 发布事件
    public void publishEvent(@NotNull ApplicationEvent event) {
       super.multicastEvent(event);
    }
}

4、配置类设计

@Configuration
public class MyListenerConfig {
    @Autowired
    private MyListener myListener;
    
    @Bean
    public MyPublisher myPublisher (){
        MyPublisher  eventPublisher = new MyPublisher();  
        eventPublisher.addApplicationListener(myListener);
         // 设置错误处理器,处理事件产生的异常信息
        eventPublisher.setErrorHandler(new WebEventErrorHandler());
        // 不能设置线程池,否则事件不会立即执行
        return eventPublisher;
    }
	 private static class WebEventErrorHandler implements ErrorHandler {
	        @Override
	        public void handleError(Throwable t) {
	            ReflectionUtils.rethrowRuntimeException(t);
	        }
	    }
}

三、如何使用

@Service
public class MyEventServiceImpl {
    @Autowired
    private MyPublisher myPublisher;
    // 调用此方法,可以自动执行监听器中的onApplicationEvent方法逻辑
    public void eventTest() {
        MyEvent myEvent = new MyEvent("张三");
        myPublisher.publishEvent(myEvent);
    }
}

你可能感兴趣的:(spring,boot,笔记)