@Async(“0-postChargeProcessor”)对应的id
<task:executor id=“0-postChargeProcessor” pool-size=“10-50” queue-capacity=“10” rejection-policy=“CALLER_RUNS”/>
目录架构
<!-- 组件扫描 -->
<context:component-scan base-package="com.zhou.task"></context:component-scan>
<!-- 异步处理请求线程池 -->
<task:executor id="0-postChargeProcessor" pool-size="10-50" queue-capacity="10" rejection-policy="CALLER_RUNS"/>
<!-- 扫描异步处理注解 -->
<task:annotation-driven />
/**
* @Author:
* @Date:2021/3/29 14:46
* @Decription: 异步发送充值线程池
*
*/
@Component
public class PostChargeProcessor {
@Autowired
ChargeOrderService chargeOrderService;
// 异步处理
@Async("0-postChargeProcessor")
public void postChange(String billId){
System.out.println("------提交充值订单------");
System.out.println("------充值订单号:"+billId);
chargeOrderService.postCharger(billId);
//调用充值业务接口
}
}
/**
* @Author:
* @Date:2021/3/29 14:49
* @Decription: 充值订单业务接口
*/
public interface ChargeOrderService {
/**
* @Auther: 周申宇
* @Date: 2021/3/29 14:49
* @Description: 发送充值订单
*
*/
String postCharger(String billId);
}
/**
* @Author:
* @Date:2021/3/29 14:50
* @Decription:
*/
@Service
public class ChargeOrderimplService implements ChargeOrderService {
@Override
public String postCharger(String billId) {
System.out.println("接收到充值订单请求,请求订单号为:"+billId);
System.out.println("处理生成订单业务");
return "success";
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.UUID;
/**
* @Author:
* @Date:2021/3/29 15:02
* @Decription: 测试异步
*/
public class TestPostChargeAsync {
public static void main(String args[]){
ManyPeople manyPeople1 = new ManyPeople();
ManyPeople manyPeople2 = new ManyPeople();
ManyPeople manyPeople3 = new ManyPeople();
ManyPeople manyPeople4 = new ManyPeople();
ManyPeople manyPeople5 = new ManyPeople();
// 模拟你异步处理的充值订单
Thread thread1 = new Thread(manyPeople1);
Thread thread2 = new Thread(manyPeople2);
Thread thread3 = new Thread(manyPeople3);
Thread thread4 = new Thread(manyPeople4);
Thread thread5 = new Thread(manyPeople5);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
class ManyPeople implements Runnable{
// 获取容器对象,注意:这个地方不能用单元测试跑,异步线程激活的是守护线程,单元测试结束
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-task.xml");
// 获取请求处理对象(手动获取,以后将这个对象使用自动装配,放到controller层)
PostChargeProcessor postChargeProcessor = applicationContext.getBean("postChargeProcessor", PostChargeProcessor.class);
@Override
public void run() {
postChargeProcessor.postChange(UUID.randomUUID().toString());
}
}