理论
在分布式场景下,实现同步转异步的方式有三种方式:
1.异步线程池执行;比如借助@Asyn注解,放到spring自带的线程池中去执行;
2.放到消息队列中,在消费者的代码中异步的消费,执行相关的逻辑;
3.基于spring的事件机制,触发事件,在监听器里实现相关逻辑;
spring中自带了事件的支持,核心类是ApplicationEventPublisher;
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直接支持的;
实战
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。