Spring、SpringBoot基于内存的异步调用ApplicationContext.publishEvent (生产、消费)

发布时间 2023-03-28 14:11:20作者: yvioo

 

ApplicationContext.publishEvent 是Spring提供的解耦的一种方式 (基于内存)。同样可以使用 MQ 组件 / 线程池 代替。

 

参数类

NotifyEvent.java

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class NotifyEvent {

    /**
     * 这里放需要传递的参数内容
     */

    private Integer id;

    private String name;
}

 

接收的客户端 消费者

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 接收异步消息的客户端
 */
@Component
@Slf4j
public class NotifyClient {

    /**
     * 异步接收客户端 相当于mq的消费者
     * @param notifyEvent  会根据这个参数进行匹配 所以这里要和生产者的参数对象对应
     */
    @EventListener
    public void notify(NotifyEvent notifyEvent){
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("参数:{}",notifyEvent.toString());
    }
}

 

使用,生产者

    @Resource
    protected ApplicationContext applicationContext;

    @GetMapping(value = "/test")
    public void test(){
        /**
         * 异步调用,相当于生产者
         * 参数通过对象传入
         */
        applicationContext.publishEvent(new NotifyEvent(1,"测试发生"));
    }