EventBus-----spring

文章介绍了如何在Spring框架中使用观察者模式来处理事件,特别是通过@EventListener注解标记监听器方法,并利用Spring的ApplicationContext进行事件发布。通过添加@Async注解,实现了事件处理的异步化,提高系统性能。示例代码展示了定义事件、监听器以及如何发布和处理事件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring也提供了一套好用的基于观察者模式的事件发布机制,
在Spring中,我们只需要将Spring管理的Bean的方法上面加上@EventListener注解,就可以将其标记为一个观察者,
可以使用ApplicationContext上下文来进行事件通知,
从下面的代码中我们可以看到,
ApplicationContext接口继承了ApplicationEventPublisher接口,可以调用publishEvent来进行事件发布,
给关注该事件的观察者发送消息,实际上ApplicationContext就相当于消息总线。

监听器定义,注意这里要加上@Component注解,可以注意到,这里使用了@Async注解,表示方法是异步执行的,这样就可以实现事件的异步发布通知啦!
当然你可以指定自定义的线程池,如果你也使用的SpringBoot,不要忘记在启动类加上@EnableAsync注解。

定义登录事件

package com.example.eventbus.spring;

import lombok.Data;

/**
 * @className: LoginEvent
 * @author: czh
 * @date: 2023/4/22
 * @Description: 定义登录事件
 * @version: 1.0.0
 **/
@Data
public class LoginEvent {
    /**
     * 用户id
     */
    private Long userId;

    /**
     * 登录类型
     */
    private Integer loginType;
}

事件监听@EventListener

/**
 * @className: LoginListener
 * @author: czh
 * @date: 2023/4/22
 * @Description: 事件监听@EventListener
 * @version: 1.0.0
 **/
@Slf4j
@Component
public class LoginListener {
    @EventListener
    @Async
    public void loginEvent(LoginEvent event) {
        log.info("监听到登录事件:" + event);
    }
}

获取Spring上下文的工具类,用于事件的发布

/**
 * @className: SpringContextHolder
 * @author: czh
 * @date: 2023/4/22
 * @Description: 获取Spring上下文的工具类,用于事件的发布
 * @version: 1.0.0
 **/
@Component
@Slf4j
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }
}

发布事件

package com.example.eventbus.spring;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @className: TestMain
 * @author: czh
 * @date: 2023/4/22
 * @Description: 发布事件
 * @version: 1.0.0
 **/
@SpringBootTest
public class TestMain {
    @Test
    public void testEventListener() throws InterruptedException {
        LoginEvent event = new LoginEvent();

        event.setLoginType(1);
        event.setUserId(8142L);

        //事件的发布
        SpringContextHolder.getApplicationContext().publishEvent(event);

        Thread.sleep(100);
    }
}

.
.
.

git参考代码: 代码
.
.
.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值