springboot事件触发event

该代码示例展示了如何在Spring框架中使用事件驱动。`CustomerController`类发布`BusinessTrackEventEntity`事件,`PublisherCustomsEvent`组件负责发布事件,而`CustomsEventListener`作为监听器对事件进行异步处理,特别是当事件类型为`BusinessTrackEventEntity`时。
摘要由CSDN通过智能技术生成

import org.example.event.BusinessTrackEventEntity;
import org.example.event.PublisherCustomsEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CustomerController {
//    @Value("${common.name}")
    private String configs;

    @Autowired
    private PublisherCustomsEvent event;

    @RequestMapping("/configs")
    public String get() {
        BusinessTrackEventEntity applicationEvent = new BusinessTrackEventEntity("开始了");
        applicationEvent.setOperation("测试");
        event.publisherEvent(applicationEvent);
        return configs;
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

@Component
public final class PublisherCustomsEvent {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void publisherEvent(ApplicationEvent applicationEvent){
        applicationEventPublisher.publishEvent(applicationEvent);
    }
}


import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Slf4j
@Component
//Application<ApplicationEvent>泛型类型也可以使用BusinessTrackEvent,如果是一个监听方法监听不同类型的事件可以使用ApplicationEvent,
// 如果针对具体某个事件的监听,泛型类型写具体的事件类型
public class CustomsEventListener implements ApplicationListener<ApplicationEvent> {

    @Async
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        try {
            if (event instanceof BusinessTrackEventEntity) {
                log.info("BusinessTrackEventEntity go ..................."+((BusinessTrackEventEntity) event).getOperation());
            }
        }catch (Exception e){
            log.info(e.getMessage());
        }
    }
}

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

@Getter
@Setter
public class BusinessTrackEventEntity extends ApplicationEvent {

    private String operation;

    public BusinessTrackEventEntity(Object source) {
        super(source);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值