网站搭建好显示建设中,郑州网球公开赛,wordpress常用主题,做外围网站犯法吗理论 在分布式场景下#xff0c;实现同步转异步的方式有三种方式#xff1a; 1.异步线程池执行#xff1b;比如借助Asyn注解#xff0c;放到spring自带的线程池中去执行#xff1b; 2.放到消息队列中#xff0c;在消费者的代码中异步的消费#xff0c;执行相关的逻辑实现同步转异步的方式有三种方式 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 ApplicationListenerEatEvent {private static final Logger logger LoggerFactory.getLogger(EatEventListener.class);Overridepublic 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;Autowiredpublic 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直接支持的 实战 完整代码地址 转载于:https://www.cnblogs.com/snidget/p/11364806.html