一、先抽象出来一个事件类继承 ApplicationEvent ,定义一个 execute 业务执行方法
/**
* @author sukang
*/
public abstract class AbstractEvent extends ApplicationEvent {
public AbstractEvent(Object source) {
super(source);
}
/**
* 事件执行方法
*/
protected abstract void execute() throws InterruptedException;
}
二、定义一个测试事件类,继承上面的抽象事件类, 重写业务方法
package com.example.demo.event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author YixinCapital -- chen.lin
*
*/
public class DemoEvent extends AbstractEvent{
private static final long serialVersionUID = 1L;
public DemoEvent(Object source) {
super(source);
}
@Override
public void execute() throws InterruptedException {
while (true) {
Thread.sleep(1000);
System.out.println("======================DemoEvent execute======================" + source);
}
}
}
三、写一个监听器
package com.example.demo.event;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* 统一事件监听器
* @author sukang
*/
@Component
public class AbstractEventListener implements ApplicationListener<AbstractEvent> {
@Override
@Async
public void onApplicationEvent(AbstractEvent event) {
try {
event.execute();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
四、ApplicationContext.publishEvent 发布事件
package com.example.demo.controller;
import com.example.demo.event.DemoEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@Autowired
private ApplicationContext ioc;
@RequestMapping("/index")
public void index () {
System.out.println("===================Java异步执行测试开始===================");
ioc.publishEvent(new DemoEvent("param"));
System.out.println("===================Java异步执行测试结束===================");
}
}
五、不要忘了在启动类上加 @EnableAsync 注解
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
六、启动项目,执行代码