【Spring】Spring的事件监听ApplicationListener 、ApplicationEvent

 

Spring中的事件监听机制,事件驱动开发
可以用在以下这些场景:
1.业务代码入口在 下一级模块module, sender消息发送者在上一级模块module,不想循环依赖,就这样用
2.解耦合的事件驱动模式,观察者模式等
3.待补充



实例代码:

1. 业务代码testAAA,执行同步业务

private void testAAA(List<ChannelInventory> channelInventories){
    try {
        List<SyncStockVO> syncRecords = new ArrayList<>();
        for (ChannelInventory channelInventory : channelInventories) {
            SyncStockVO syncStockVO = new SyncStockVO();
            syncStockVO.setId(channelInventory.getId());
            syncStockVO.setSkuId(channelInventory.getSkuId());
            ......
            syncRecords.add(syncStockVO);
        }
        omsStockSyncHelper.sendStockStatusChangeMsg(syncRecords);

        log.error("同步 完成,request:{}", JSON.toJSONString(syncRecords));
    } catch (Exception e) {
        String errMsg = "同步 异常";
        log.error(errMsg, e);
        retrySyncStock(channelInventories);
    }
}

 

 

2.事件发布助手 OmsStockSyncHelper

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;

@Component
public class OmsStockSyncHelper {
    @Resource
    private ApplicationEventPublisher publisher;

    public void sendStockStatusChangeMsg(List<SyncStockVO> vos){
        publisher.publishEvent(new OmsStockSyncEvent(vos));
    }
}

 

 

3.事件体,必须是ApplicationEvent的子类

import org.springframework.context.ApplicationEvent;
import java.util.List;

public class OmsStockSyncEvent  extends ApplicationEvent {

    private static final long serialVersionUID = -2926756513711326075L;
    private List<SyncStockVO> vos;
    /**
     * 时间戳
     */
    private Long time;

    public List<SyncStockVO> getVos() {
        return vos;
    }

    public void setVos(List<SyncStockVO> vos) {
        this.vos = vos;
    }

    public Long getTime() {
        return time;
    }

    public void setTime(Long time) {
        this.time = time;
    }

    public OmsStockSyncEvent(List<SyncStockVO> volist) {
        super("OmsStockSyncEvent");
        vos = volist;
        time = System.currentTimeMillis();
    }
}

 

 

4.事件捕获者,必定是实现了ApplicationListener的类

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Slf4j
@Service
public class OmsStockSyncHandler implements ApplicationListener<OmsStockSyncEvent> {

    @Resource
    private OmsStockMsgSender sender;
    
    
    //事件捕获之后,你怎么处理,就按自己的业务处理咯,这里示例是发送MQ,所以写了一个sender
    @Override
    public void onApplicationEvent(OmsStockSyncEvent event) {
        sender.send(event);
    }
}

 

 

 



posted @ 2024-03-04 16:43  Angel挤一挤  阅读(7)  评论(0编辑  收藏  举报