spring 使用@Async注解实现异步调用

本文详细介绍了如何在Spring框架中实现事件监听与异步任务处理,包括自定义事件类、事件监听器的定义与注册,以及如何利用@EnableAsync和@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(事件监听器)。

转载于:https://www.cnblogs.com/lxjy201832/p/10517814.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值