通过ApplicationContextAware获取上下文,然后监听实现异步操作
先定义一个监听事件
public class ApplicationEventTest extends ApplicationEvent {
/**
* Create a new {@code ApplicationEvent}.
*
* @param source the object on which the event initially occurred or with
* which the event is associated (never {@code null})
*/
public ApplicationEventTest(Object source) {
super(source);
}
}
创建监听主体容器
@Service//@EventLsitener需要在component执行
public class ApplicationEventListenTest {
@Order
@EventListener(ApplicationEventTest.class)//监听规定事件
//默认这种事件机制是同步的
@Async//开启异步
public void applicationEventTest(ApplicationEventTest event) {
String jsonStr = JSONUtil.toJsonStr(event.getSource());
JSONObject parse = (JSONObject)JSONObject.parse(jsonStr);
System.out.println("parse = " + parse);
try {
System.out.println("测试异步" +1 );
TimeUnit.SECONDS.sleep(2);
System.out.println("测试异步" +2 );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
实现
@Autowired
private ApplicationContext applicationContext;
@Autowired
private InnerCalssAsync innerCalssAsync;
@Autowired
private DiaService diaService;
@GetMapping("/run")
public void run(){
eventParam eventParam = new eventParam();
eventParam.setKey("key");
eventParam.setName("name");
//上下文去推事件触发监听器
// innerCalssAsync.asyncRun();//跨类async才生效:原因是async走aop,同一个类型没走代理
SpringContextHolder.publishEvent(new ApplicationEventTest(eventParam));//对applicationContext判空
System.out.println("测试异步" +3 );
// applicationContext.publishEvent(new ApplicationEventTest(eventParam));
只要监听事件和监听容器,监听容器具体实现