springboot3 事件驱动开发例子

目录结构

代码

LoginController

@RestController
public class LoginController {

    @Autowired
    EventPublisher eventPublisher;

    @GetMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("passwd") String passwd) {
        // 业务处理登录
        System.out.println("业务处理登录完成....");

        //TODO 发送事件
        //1、创建事件信息
        LoginSuccessEvent event = new LoginSuccessEvent(new UserEntity(username, passwd));
        //2、发送事件
        eventPublisher.sendEvent(event);

        return username + "登录成功";

    }
}

UserEntity

@AllArgsConstructor
@NoArgsConstructor
@Data
public class UserEntity {
    private String username;
    private String passwd;
}

EventPublisher

@Service
public class EventPublisher implements ApplicationEventPublisherAware {
    // 底层发送事件用的组件,SpringBoot会通过ApplicationEventPublisherAware接口自动注入给我们
    // 事件是广播出去的。所有监听这个事件的监听器都可以收到
    ApplicationEventPublisher applicationEventPublisher;

    // 所有事件都可以发
    public void sendEvent(ApplicationEvent event) {
        //调用底层API发送事件
        applicationEventPublisher.publishEvent(event);
    }


    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}

LoginSuccessEvent

public class LoginSuccessEvent extends ApplicationEvent {
    // source代表是谁登录成了
    public LoginSuccessEvent(UserEntity source){
        super(source);
    }
}

AccountService

@Order(2)
@Service
public class AccountService implements ApplicationListener<LoginSuccessEvent> {

    public void addAccountScore(String username) {
        System.out.println(username + "加了1分");
    }
    @Override
    public void onApplicationEvent(LoginSuccessEvent event) {
        System.out.println("AccountService 收到事件 ======");

        UserEntity source = (UserEntity) event.getSource();
        addAccountScore(source.getUsername());
    }
}

CouponService

@Service
public class CouponService {

    public void sendCoupon(String username){
        System.out.println(username + "随机得到了一张优惠券");
    }

    @Order(1)
    @EventListener
    public void onEvent(LoginSuccessEvent loginSuccessEvent){
        System.out.println("CouponService 收到事件 ======");
        UserEntity source = (UserEntity) loginSuccessEvent.getSource();
        sendCoupon(source.getUsername());
    }

}

测试

启动访问流量器
http://127.0.0.1:8080/login?username=klvchen&passwd=12345

效果

posted @ 2023-09-13 15:43  klvchen  阅读(88)  评论(0)    收藏  举报