spring的事件机制实战

理论

在分布式场景下,实现同步转异步的方式有三种方式:

1.异步线程池执行;比如借助@Asyn注解,放到spring自带的线程池中去执行;

2.放到消息队列中,在消费者的代码中异步的消费,执行相关的逻辑;

3.基于spring的事件机制,触发事件,在监听器里实现相关逻辑;

spring中自带了事件的支持,核心类是ApplicationEventPublisher;

事件包括三个要点:下面是一个demo的实现,理论结合实战。

1 事件的定义;

package com.springbootpractice.demoevent.event;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent; /**
* @说明 吃饭事件
* @作者 carter
* @创建时间 2019年07月12日 13:12
**/
public class EatEvent extends ApplicationEvent { private static final Logger logger = LoggerFactory.getLogger(EatEvent.class); private Boolean eatFinished; public EatEvent(Boolean eatFinished) {
super(eatFinished);
this.eatFinished = eatFinished;
} public void callGirlFriend() {
logger.info("美女,吃完饭了,来收拾一下吧!");
} public void callBrothers() {
logger.info("兄弟们,吃完饭了,来打dota !");
} public Boolean getEatFinished() {
return eatFinished;
}
}

2 事件监听的定义;

package com.springbootpractice.demoevent.event.listener;

import com.springbootpractice.demoevent.event.EatEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component; import java.util.Objects; /**
* 说明: XEvent的事件监听器
*
* @author carter
* 创建时间 2019年07月12日 13:19
**/
@Component
public class EatEventListener implements ApplicationListener<EatEvent> { private static final Logger logger = LoggerFactory.getLogger(EatEventListener.class); @Override
public void onApplicationEvent(EatEvent xEvent) {
if (Objects.isNull(xEvent)) {
return;
} if (xEvent.getEatFinished()) {
xEvent.callGirlFriend();
logger.info("xxxx,女朋友拒绝收拾!");
xEvent.callBrothers();
logger.info("满人了,下次带你!");
} }
}

3 发布事件;

package com.springbootpractice.demoevent.web;

import com.springbootpractice.demoevent.event.EatEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; /**
* 说明 测试控制器
*
* @author carter
* 创建时间 2019年07月12日 13:23
**/
@RestController
public class TestController { private final ApplicationEventPublisher applicationEventPublisher; @Autowired
public TestController(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
} @GetMapping(path = "/eatOver")
public Object eatOver() {
EatEvent xEvent = new EatEvent(true);
applicationEventPublisher.publishEvent(xEvent);
return "eat over and publish event success";
} }

无需多余的配置,springmvc直接支持的;

实战

完整代码地址

上一篇:Spring的事件发布机制


下一篇:Daily Scrum 10.21