美文网首页【每天学点Spring】
【每天学点Spring】Spring Events

【每天学点Spring】Spring Events

作者: 伊丽莎白2015 | 来源:发表于2022-04-17 16:41 被阅读0次

事件驱动设计模式,也可能通过Spring来实现。

围绕事件的三个角色

  • 事件(Event)
  • 事件发布者(Publisher)
  • 事件监听者(Listener)

文章内容:

Spring Event.jpg

1. Demo-01: Spring 4.2版本前

  • 在Spring4.2之前,Event 需要继承ApplicationEvent类。
  • Publisher 需要注入类:ApplicationEventPublisher.
  • Listener 需要实现接口ApplicationListener。

默认情况下,事件的发布和执行都是同步的,这样做的好处是监听的方法也可以参与到发布事件类的transaction中。

1.1 先是Event类:
@Getter
public class UserCreateEvent extends ApplicationEvent {
    private String userId;

    public UserCreateEvent(Object source, String userId) {
        super(source);
        this.userId = userId;
    }
}
1.2 Publisher类:

有两种方式可以实现:

  1. 如示例中的代码,注入ApplicationEventPublisher对象。
  2. 可以实现接口ApplicationEventPublisher。
@Slf4j
@Service
public class UserCreateService {
    @Autowired
    public ApplicationEventPublisher applicationEventPublisher;

    public boolean addUser(String userId) {
        log.info("Start to add user.");
        applicationEventPublisher.publishEvent(new UserCreateEvent(this, userId));
        log.info("Add user done.");
        return true;
    }
}
1.3 Listener类:
@Slf4j
@Component
public class UserCreateListener implements ApplicationListener<UserCreateEvent> {
    public void onApplicationEvent(UserCreateEvent userCreateEvent) {
        String userId = userCreateEvent.getUserId();
        log.info("Start to notify user.");

        // mock service, cost 3 second to send email:
        ThreadUtils.sleep(3000L);

        log.info("Finished notifying user for userId = " + userId);
    }
}
1.4 Test类:
@SpringBootTest
public class UserCreateServiceTest {
    @Autowired
    private UserCreateService userCreateService;

    @Test
    public void addUserTest() {
        userCreateService.addUser("testUser1");
    }
}

打印结果:可以看到Listener的代码是同步的,Add user done等到Listener代码执行后才打印:

2022-04-17 15:24:56.857 INFO 21545 --- [ main] UserCreateService : Start to add user.
2022-04-17 15:24:56.858 INFO 21545 --- [ main] UserCreateListener : Start to notify user.
2022-04-17 15:24:59.863 INFO 21545 --- [ main] UserCreateListener : Finished notifying user for userId = testUser1
2022-04-17 15:24:59.864 INFO 21545 --- [ main] UserCreateService : Add user done.

2. Demo-02:在Spring 4.2版本前,想要异步事件,需要额外定义BeanApplicationEventMulticaster:

@Configuration
public class AsynchronousSpringEventsConfig {
    @Bean(name = "applicationEventMulticaster")
    public ApplicationEventMulticaster simpleApplicationEventMulticaster() {
        SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster();

        eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
        return eventMulticaster;
    }
}
Test类:
@SpringBootTest
public class UserCreateServiceTest {
    @Autowired
    private UserCreateService userCreateService;

    @Test
    public void addUserTest() {
        userCreateService.addUser("testUser1");
        ThreadUtils.sleep(5000L); //等5秒,为了等Listener执行完毕
    }
}

打印结果:可以看到Listener的代码是异步的,Add user done没有等到Listener代码执行后才打印,并且线程池名称也能看出Listener用的不是Main主线程:

2022-04-17 15:30:03.329 INFO 21549 --- [ main] UserCreateService : Start to add user.
2022-04-17 15:30:03.331 INFO 21549 --- [TaskExecutor-18] UserCreateListener : Start to notify user.
2022-04-17 15:30:03.331 INFO 21549 --- [ main] UserCreateService : Add user done.
2022-04-17 15:30:06.336 INFO 21549 --- [TaskExecutor-18] UserCreateListener : Finished notifying user for userId = testUser1

3. demo-03: Spring 4.2版本后,基于Annotation注解的事件驱动模型:

3.1 @EventListener

Listener不需要再实现接口ApplicationListener,而是可以直接在方法上加注解@EventListener:

@Slf4j
@Component
public class UserCreateListenerWithAnnotation {
    @EventListener
    public void onApplicationEvent(UserCreateEvent userCreateEvent) {
        // 实现同UserCreateListener
    }
}
3.2 @Async

异步事件可以使用@Async注解:

@Slf4j
@Component
public class UserCreateListenerWithAnnotation {
    @Async
    @EventListener
    public void onApplicationEvent(UserCreateEvent userCreateEvent) {
        // 实现同UserCreateListener
    }

使用@Async需要开启:@EnableAsync

@SpringBootApplication
@EnableAsync
public class SpringProjectApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringProjectApplication.class, args);
    }
}
3.3 Event类支持泛型,且不需要继承ApplicationEvent:

注:在做测试的时候,别忘记给新的GenericUserCreateEvent类加上Publisher。

@Getter
public class GenericUserCreateEvent<T> {
    private T userId;
    private boolean success;

    public GenericUserCreateEvent(T userId, boolean success) {
        this.userId = userId;
        this.success = success;
    }
}
3.4 Listener支持condition,使用SpEL表达式来定义触发的条件:

以下示例是condition结合支持泛型的Event类:

@Slf4j
@Component
public class UserCreateListenerWithAnnotation {
    @EventListener(condition = "#event.success")
    public void onApplicationEvent(GenericUserCreateEvent event) {
        String userId = (String)event.getUserId();
        log.info("Finished notifying user for userId = " + userId);
    }

}

举例:

  • condition = "#event.success": 匹配event.getSuccess() == true时,才会触发。
  • condition = "#event.type eq 'email'": 匹配event.getType()等于email时,才会触发。
  • condition = "#event.type ne 'email'": 匹配event.getType()不等于email时,才会触发。

3.5 还可以监听多个事件:

@EventListener(classes = { ContextStartedEvent.class, ContextStoppedEvent.class })

4. 扩展

4.1 Spring自带的Event:

除了自定义Event类,Spring框架也定义了一系列的Event,我们可以自定义Listener来监听这些事件,例如:

  • ContextRefreshedEvent:执行了ConfigurableApplicationContext#refresh()方法
  • ContextStartedEvent:执行了ConfigurableApplicationContext#start()方法
  • ContextStoppedEvent:执行了ConfigurableApplicationContext#stop()方法
  • ContextClosedEvent:执行了ConfigurableApplicationContext#close()方法
4.2 @TransactionalEventListener

Spring 4.2版本后,新定义了一个注解叫@TransactionalEventListener,是@EventListener的扩展,从名字也可以看出,这个注解跟事务有关。

我们可以定义不同的phase(阶段):

  1. AFTER_COMMIT (默认):在事务成功提交后执行。
  2. AFTER_ROLLBACK:事件被rollback后执行。
  3. AFTER_COMPLETION – 事务完成后提交 (包含上述#1 #2两个阶段)。
  4. BEFORE_COMMIT:在事件提交前执行。

示例:

@Slf4j
@Service
public class UserCreateListenerTransaction {

    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
    public void onApplicationEvent(GenericUserCreateEvent event) {
        // 实现同UserCreateListenerWithAnnotation
    }

}

上述的Listener代码何时被触发?当publisher代码有事务被且将要被提交时才会触发。

Publisher示例,可以看到addUserOnlySuccessNotify方法需要加上@Transactional才可以触发上述的UserCreateListenerTransaction#onApplicationEvent()方法:

@Slf4j
@Service
public class UserCreateService {
    @Autowired
    public ApplicationEventPublisher applicationEventPublisher;

    @Transactional
    public boolean addUser(String userId) {
        log.info("Start to add user.");

        applicationEventPublisher.publishEvent(new GenericUserCreateEvent(userId, true));
        log.info("Add user done.");
        return true;
    }
}

执行Test类后,打印如下,注意打印顺序,addUser先执行后再执行Listener:

2022-04-17 17:41:31.334 INFO 21729 --- [ main] UserCreateService : Start to add user.
2022-04-17 17:41:31.335 INFO 21729 --- [ main] UserCreateService : Add user done.
2022-04-17 17:41:31.336 INFO 21729 --- [ main] UserCreateListenerTransaction : Start to notify user.
2022-04-17 17:41:34.341 INFO 21729 --- [ main] UserCreateListenerTransaction : Finished notifying user for userId = testUser2

也就是说,如果Publisher方法没有事务,Listener中的方法将不会被触发。除非加上fallbackExecution = true
即:

@TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, fallbackExecution = true)

改成上述的注解后,即便Publisher方法没有事务,Listener也会执行。


【参考】
Spring Event: https://www.baeldung.com/spring-events
Spring Application Context Event: https://www.baeldung.com/spring-context-events
How to do @Async in Spring: https://www.baeldung.com/spring-async#enable-async-support
Spring expression langurage: https://www.baeldung.com/spring-expression-language

相关文章

网友评论

    本文标题:【每天学点Spring】Spring Events

    本文链接:https://www.haomeiwen.com/subject/kkzqertx.html