spring 异步执行任务方法(@Async注解代替多线程 )--学习

1 篇文章 0 订阅
1 篇文章 0 订阅

最近在开发过程里遇到让人很头痛的功能,就是一个批量复制功能,批量复制中包括数据库中的数据,还有文件系统的复制。这在开发中要考虑到系统性能和友好度的问题,一个批量复制最少要执行1~3分钟,这让用户在点击一个按钮后要等待1~3分钟不现实,最后只能用多线程,来达到用户的友好度。

 

在项目既然用到了Spring ,我们用Spring实现的多线程来实现这个功能。

public class JobUtilsTest{  
      
    @Autowired  
    private DaoService service;  
  
    @Test  
    public void testAsync() throws Exception {  
        System.out.println("start" );  
        service.update(); // ★ 假设这个方法会比较耗时,需要异步执行  
        System.out.println("end");  
          
          
        Thread.sleep(3000); // 因为junit结束会结束jvm,所以让它等会异步线程  
    }  
}  

在方法上加@Async注解 这个方法就成异步方法了

异步方法不能和调用方法放在一个类里面

@Service  
public class DaoService {  
   @Async
    public void update() {  
        try {  
            Thread.sleep(2000);  
            // do something  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        System.out.println("operation complete.");  
    }  
}  

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">  
  
    <context:component-scan base-package="com.chinacache" />
    <!--Spring 的配置文件中一定要配置这一项 -->
    <task:annotation-driven/> 
</beans>
 
输出结果:
start
end
operation complete.
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值