SpringBoot中ApplicationEvent的用法

介绍

 ApplicationEvent类似于MQ,是Spring提供的一种发布订阅模式的事件处理方式。相对于MQ,其局限在于只能在同一个Spring容器中使用。

使用步骤

封装消息

将要发送的内容,封装成一个bean,这个bean需要继承ApplicationEvent类。

package com.example.event;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.context.ApplicationEvent;

/**
 * @Description: 封装消息
 * @author: zeal
 * @date: 2024年04月09日 10:22
 */
@Setter
@Getter
@ToString
public class UserLoginEvent extends ApplicationEvent {

    private Integer userId;

    private String token;

    public UserLoginEvent(Object source,Integer userId,String token) {
        super(source);
        this.userId=userId;
        this.token=token;
    }
}

推送消息

推送消息时,注入ApplicationEventPublisher或ApplicationContext均可,调用publishEvent()方法。

package com.example.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description: 消息推送
 * @author: zeal
 * @date: 2024年04月09日 10:26
 */
@RestController
@RequestMapping("event")
public class UserLoginController {
    @Autowired
    private ApplicationContext applicationContext;
    
    @RequestMapping("/push")
    public void pushEvent(){
        UserLoginEvent userLoginEvent=new UserLoginEvent(this,001,"zsaf");
        applicationContext.publishEvent(userLoginEvent);
    }
}

监听消息

此步骤相当于MQ的消费者,实现ApplicatonListener类,通过泛型来设置消息类型。

package com.example.event;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @Description: 监听消息
 * @author: zeal
 * @date: 2024年04月09日 10:25
 */
@Component
public class UserLoginEventListener implements ApplicationListener<UserLoginEvent> {
    @Override
    public void onApplicationEvent(UserLoginEvent event) {
        System.out.println("收到消息:"+event.toString());
    }
}

通过注解实现监听

package com.example.event;

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * @Description: 监听消息
 * @author: zeal
 * @date: 2024年04月09日 10:25
 */
@Component
public class UserLoginEventListener{
    @EventListener
    public void onApplicationEvent(UserLoginEvent event) {
        System.out.println("收到消息:"+event.toString());
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值