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

 

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;
import org.springframework.scheduling.annotation.EnableAsync;
/** * 接收异步消息的客户端 */
@EnableAsync //开启异步 ,如果已经加了就不用加了 @Component @Slf4j public class NotifyClient { /** * 异步接收客户端 相当于mq的消费者 * @param notifyEvent 会根据这个参数进行匹配 所以这里要和生产者的参数对象对应 */ @Async
@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,"测试发生"));
    }

 

如果不能注入调用 可以参考:

Spring工具类 非spring管理环境中获取bean及环境配置:https://www.cnblogs.com/pxblog/p/15065785.html

 

 ApplicationContextUtil.getApplicationContext().publishEvent(new NotifyEvent(1,"测试发生"));

 

posted @ 2023-03-28 14:06  yvioo  阅读(495)  评论(0编辑  收藏  举报