SpringBoot之异步事件监听

SpringBoot之异步事件监听

  • 一、注册一个事件
  • 二、注册多个事件监听
  • 三、事件发布
  • 总结


一、注册一个事件

public class UserRegisterEvent extends ApplicationEvent {
    private String username;

    public UserRegisterEvent(Object source) {
        super(source);
    }

    public UserRegisterEvent(Object source, String username) {
        super(source);
        this.username = username;
    }

    public String getUsername() {
        return username;
    }
}

二、注册多个事件监听

@Service
public class EmailService implements ApplicationListener<UserRegisterEvent> {
    /**
     * 监听用户注册事件, 异步发送执行发送邮件逻辑
     */
    @Override
    @Async
    public void onApplicationEvent(UserRegisterEvent event) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("给" + event.getUsername() + "发送邮件");
    }
}

@Service
public class PhoneService  implements ApplicationListener<UserRegisterEvent> {
    @Override
    @Async
    public void onApplicationEvent(UserRegisterEvent event) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("给" + event.getUsername() + "打电话");
    }
}

注意: SpringBoot启动类上需要加@EnableAsync才能支持异步的注解

三、事件发布

@RestController
public class TestController {
    @Autowired
    private ApplicationContext applicationContext;

    @RequestMapping("add")
    public void addUser(){
        String username = "小明";
        applicationContext.publishEvent(new UserRegisterEvent(this, username));
    }
}

总结

1.解耦,增加了代码的可拓展性,符合开闭原则
2.使用异步的方式执行更快

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