1)线程池的配置:
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="3" /> <property name="keepAliveSeconds" value="200" /> <property name="maxPoolSize" value="5" /> <property name="queueCapacity" value="25" /> </bean>
配置过程中观注上面最重要的四个属性的配置。
2)创建线程处理事务逻辑的类,类要实现Runnable接口。代码如下:
public class InitCategoryThreadHandle implements Runnable {
private CategoryManager categoryManager;
private Long merchantId;
public InitCategoryThreadHandle (CategoryManager categoryManager, Long merchantId) {
this.categoryManager = categoryManager;
this.merchantId = merchantId;
}
@Override
public void run() {
categoryManager.initCacheCatgoryByMerchantId(merchantId);
}
}
业务逻辑中用到的参数通过构造方式赋值。
3)创建调用线程的中间类。代码如下:
@Service("asynBusiness")
public class AsynBusiness {
@Resource
private TaskExecutor taskExecutor;
@Resource
private CategoryManager categoryManager;
public void asynInitCategory(Long merchantId){
InitCategoryThreadHandle categoryThread = new InitCategoryThreadHandle(categoryManager, merchantId);
taskExecutor.execute(categoryThread);
}
}
4)业务方法中直接使用asyBusiness中的方法,来启动线程。对业务方法只暴露asyBusiness,这种方式,程序的可扩展性大增强。