spring 使用@Async注解实现异步调用
1.先定义一个事件,该类继承 ApplicationEven的抽象类
import org.springframework.context.ApplicationEvent; public class DemoTask extends ApplicationEvent { private String id; public OrgRegisterTask(Object source, Stringid) { super(source); this.id = id; } public String getId() { return id; } }
2.定义一个监听者,时刻监听者发布者是否有发布任务。
import com.alibaba.fastjson.JSON; import com.xxx.event.OrgRegisterTask; import com.xxx.service.DemoService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Component; @Slf4j @Component @EnableAsync public class DemoTaskHandler { @Autowired private DemoService demoService; @EventListener @Async public void demoHandler(DemoTask demoTask) { demoService.registerAccount(demoTask.getId()); } }
3.事件发布
import javax.annotation.Resource; import org.springframework.context.ApplicationEventPublisher; @Component public class DemoPubLisher { @Resource private ApplicationEventPublisher publisher; //事件发布方法 public void pushListener(String id){ publisher.publishEvent(new DemoTask(this,id)); } }
在类上,我们增加了注解@EnableAsync 表示开启异步@Async注解,不使用@EnableAsync注解,@Async是不会生效的;@Component 把bean注册到spring容器中;.在方法上我们使用了@EventListener(事件监听器)。