spring注解式异步实例

  1. 首先我们需要在调用异步方法的类型添加如下注解
@Configuration
@EnableAsync
  1. 然后再异步的方法上添加如下注解
@Async

这样就可以使用了

实例如下:

/**
 * 调到异步方法类
 */
@Configuration
@EnableAsync
public class PmZdfa extends Node{

	@Autowired
	private AsySendMsg asySendMsg;
	
	@Override
	public EnginResponse excute(EnginRequest enginRequest) {
	    
	    Thread thread = Thread.currentThread();
        System.out.println("================Thread: " + thread);
        System.out.println("================Thread Id: " + thread.getId());
        System.out.println("================Thread Name: " + thread.getName());
        System.out.println("================Thread Group: " + thread.getThreadGroup());
        System.out.println("================Thread Priority: " + thread.getPriority());
	    asySendMsg.sendMsg();
}

/**
 * 异步方法具体实现
 */
@Component("asySendMsg")
public class AsySendMsg {
    
    @Autowired
    private ISysMsgInterface iSysMsgInterface;
    
    @Async
    public void sendMsg(){
        Thread thread = Thread.currentThread();
        System.out.println("================Thread: " + thread);
        System.out.println("================Thread Id: " + thread.getId());
        System.out.println("================Thread Name: " + thread.getName());
        System.out.println("================Thread Group: " + thread.getThreadGroup());
        System.out.println("================Thread Priority: " + thread.getPriority());
    }
}


//控制台输出:
================Thread: Thread[DubboServerHandler-10.40.231.184:20985-thread-19,5,main]
================Thread Id: 59
================Thread Name: DubboServerHandler-10.40.231.184:20985-thread-19
================Thread Group: java.lang.ThreadGroup[name=main,maxpri=10]
================Thread Priority: 5
================Thread: Thread[SimpleAsyncTaskExecutor-1,5,main]
================Thread Id: 60
================Thread Name: SimpleAsyncTaskExecutor-1
================Thread Group: java.lang.ThreadGroup[name=main,maxpri=10]
================Thread Priority: 5

你可能感兴趣的:(Spring)