Springboot2(13)轻松搞定自定义事件监听

版权声明:转载请注明出处 https://blog.csdn.net/cowbin2012/article/details/85247875

源码地址

实现监听方式三步骤:

1.自定义事件一般继承ApplicationEvent

2.定义事件监听实现ApplicationContextListener

3.发布事件

定义一个自定义事件,继承ApplicationEvent类

@Data
@AllArgsConstructor
public class LogPojo {
    private String logName;
}

@Getter
public class LogSaveEvent  extends ApplicationEvent{
	public LogPojo logPojo;
	public LogSaveEvent(Object source,LogPojo logPojo) {
		super(source);
		this.logPojo = logPojo;
		// TODO Auto-generated constructor stub
	}
	public LogSaveEvent (Object source) {
		super(source);
	}
}

事件监听实现

@Component
@Slf4j
public class LogEventListener {
    @EventListener
    @Async
    public void saveLog(LogSaveEvent event) throws InterruptedException{
        log.info("LogEventListener:"+event.getLogPojo().getLogName());
    }
}

或者

@Slf4j
@Component
public class LogEvent2Listener implements ApplicationListener<LogSaveEvent> {
    @Async
    @Override
    public void onApplicationEvent(LogSaveEvent logSaveEvent) {
        log.info("LogEvent2Listener:"+logSaveEvent.getLogPojo().getLogName());
    }
}

发布事件

@RestController
public class EventController {
    @Autowired
    private ApplicationContext publisher;

    @RequestMapping("/publisher")
    public String publisher(){
        LogSaveEvent event = new LogSaveEvent(this,new LogPojo("tom"));
        publisher.publishEvent(event);
        return "success";
    }
}

结果

2018-12-21 12:14:18.485  INFO 8376 --- [      default-2]      : LogEvent2Listener:tom
2018-12-21 12:14:18.488  INFO 8376 --- [      default-1]      : LogEventListener:tom

@Async实现异步监听

猜你喜欢

转载自blog.csdn.net/cowbin2012/article/details/85247875