我从数据库中获取作业。我想从DB获取记录是单线程的。一旦我完成了所有工作,我希望它们可以并行执行多个线程。
答案 0 :(得分:0)
正如你所说,你正在使用Spring,我建议你查一下their documentation。
然后,您可以让您的线程查询数据库将您的工作(包含在Callable
或Runnable
中)提交到ThreadPoolTaskExecutor
。
答案 1 :(得分:0)
我正在将每个客户的处理传递给线程池。
.....
@Autowired
ThreadPoolTaskExecutor taskExecutor;
@Autowired
private ApplicationContext applicationContext;
@Transactional
public void processPendingPayments() {
logger.debug("ProcessPendingPayments.processPendingPayments begins");
logger.info("startTime::" + System.currentTimeMillis());
List<PaymentRequestEntity> recordsPendingForPayment = getRecordsPendingForPayment();
// Group Requests with Customers
Map<String, List<PaymentRequestEntity>> customerPaymentRequestsMap = getPendingRecordsGroupedByCustomer(
recordsPendingForPayment);
// process Payment requests for customers
for (String customerId : customerPaymentRequestsMap.keySet()) {
CustomerPaymentRequestProcessor customerPaymentRequestProcessor = (CustomerPaymentRequestProcessor) applicationContext
.getBean("customerPaymentRequestProcessor");
customerPaymentRequestProcessor.setStrCustomerId(customerId);
customerPaymentRequestProcessor.setCustomerPaymentRequestsMap(customerPaymentRequestsMap);
taskExecutor.execute(customerPaymentRequestProcessor);
}
logger.info("endTime::" + System.currentTimeMillis());
logger.debug("ProcessPendingPayments.processPendingPayments ends");
}
........
以下是Runnable类的代码,用于处理每个客户的记录
@Component
@Scope("prototype")
public class CustomerPaymentRequestProcessor implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(CustomerPaymentRequestProcessor.class);
private String strCustomerId;
private Map<String, List<PaymentRequestEntity>> customerPaymentRequestsMap;
private final String REQUEST_TYPE_BALANCE = "Balance";
@Autowired
private BalanceServiceImpl balanceServiceImpl;
@Autowired
PendingPaymentsSequenceProcessor pendingPaymentsSequenceProcessor;
@Autowired
CustomerAuditServiceImpl customerAuditServiceImpl;
public CustomerPaymentRequestProcessor() {
}
public CustomerPaymentRequestProcessor(String strCustomerId,
Map<String, List<PaymentRequestEntity>> customerPaymentRequestsMap) {
super();
this.strCustomerId = strCustomerId;
this.customerPaymentRequestsMap = customerPaymentRequestsMap;
}
@Override
public void run() {
logger.debug("CustomerPaymentRequestProcessor.run starts");
List<PaymentRequestEntity> paymentRequests = getCustomerPaymentRequestsMap().get(getStrCustomerId());
for (PaymentRequestEntity paymentRequest : paymentRequests) {
CustomerBalanceResponse customerBalanceResponse = processPaymentRequest(paymentRequest);
if (!customerBalanceResponse.isCustomerHasBalance()
&& REQUEST_TYPE_BALANCE.equals(paymentRequest.getRequestType())) {
break;
}
}
logger.debug("CustomerPaymentRequestProcessor.run ends");
}
....
....
}