事件生产和监听

事件的生产者

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class Sender {
    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 发布事件
     * @param eventBoat 事件数据
     * @Return 调用结果
     */
    public boolean sendEvent(EventBoat eventBoat) {
        boolean flag = false;
        try {
            applicationContext.publishEvent(eventBoat);
            flag = true;
            log.info("发送事件成功");
        } catch (Exception e) {
            log.error("发送事件失败,eventBoat={}", JSON.toJSONString(eventBoat));
        }
        return flag;
    }
}

事件的监听者

@Component
@Slf4j
public class Listener {
    /**
     * 处理事件
     * @param eventBoat
     * @Return
     */
    @EventListener
    @Async
    public void handleEvent(EventBoat eventBoat){
        try {
            String batchNo = eventBoat.getBatchNo();
            log.info("事件接收成功:{}", batchNo);
            //业务处理
            ...........
        } catch (Exception e) {
            log.error("处理执行错误>>> {}", e);
        }
    }

}

实体类

@Data
public class EventBoat extends ApplicationEvent {
    /**
     * 批次号
     */
    private String batchNo;

    public EventBoat(Object source, String batchNo) {
        super(source);
        this.batchNo = batchNo;
    }
}
posted @ 2021-11-10 09:21  紫川先生  阅读(24)  评论(0编辑  收藏  举报