springboot(mvc)利用applicationEvent来解耦异步运行很实用。
By:Roy.LiuLast updated:2020-04-22
但一个对象的变化,触发另外一个事件。只是典型的观察者模式,在spring中也有很好的体现,ApplicationEvent 就是很好的一个实现。简单记录几个要点:
1. 对象(事件)
2. 监听对象
3. 发布对象
分别写了几个简单的类来实现:
1. 事件本身
2. 监听器
4. 事件触发的service. 一个测试,模拟等待几秒
5. 如果想异步执行,还需要开启 @EnableAsync
1. 对象(事件)
2. 监听对象
3. 发布对象
分别写了几个简单的类来实现:
1. 事件本身
public class LogEvent extends ApplicationEvent { private Logger logger = LoggerFactory.getLogger(this.getClass()); public LogEvent(Object source) { super(source); logger.info("log event construstor function"); } }
2. 监听器
@Component public class LogEventListener { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private LogEventService logEventService; @EventListener @Async public void onApplicationEvent(LogEvent logEvent) { logger.info("==>onAppliation Event begin"); try { logEventService.testLogEvent(); } catch (InterruptedException e) { e.printStackTrace(); } logger.info("==>onAppliation Event end"); } } 3. 触发监听,也就是发布事件, 我放在controller里测试 [code] @RestController @RequestMapping("/event") public class EventController { @Autowired private ApplicationEventPublisher publisher; @RequestMapping("/log") public String testEventLog() { String s = "lalalala" + System.currentTimeMillis(); LogEvent e = new LogEvent("lalalala" + System.currentTimeMillis()); publisher.publishEvent(e); return s; } }
4. 事件触发的service. 一个测试,模拟等待几秒
@Service public class LogEventService { private Logger logger = LoggerFactory.getLogger(this.getClass()); public void testLogEvent() throws InterruptedException { logger.info("==begin to asyn exec function"); Thread.sleep(5000); logger.info("I am done"); logger.info("==end to asyn exec function"); } }
5. 如果想异步执行,还需要开启 @EnableAsync
From:一号门
Previous:做一个mysql监控系统应该掌握的一些基本语句
Next:积木长恨歌
COMMENTS