@Controller
@AllowAnonymous
@RequestMapping("/api/message")
public class MessageApiController {
@Autowired
private RemindQueueService remindQueueService;//主线程的service,需要被子线程使用
@RequestMapping(value = "/send", method = RequestMethod.GET)
@ResponseBody
public DataResult sendMessage(long orgid) {
DataResult result = new DataResult();
//取出所有需要提醒的内容
List<RemindQueue> remindList = remindQueueService.listRemindQueue();
ThreadPoolExecutor executor = new ThreadPoolExecutor(50, 100, 200, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(500));
for (RemindQueue remindQueue : remindList) {
MessageTask messageTask = new MessageTask(remindQueue, remindQueueService);//通过参数的形式将service的实例传递给线程池中使用
executor.execute(messageTask);
}
return result;
}
class MessageTask implements Runnable {
private RemindQueue remindQueue;
private RemindQueueService remindQueueService;
public MessageTask(RemindQueue queue, RemindQueueService remindService) {
remindQueueService = remindService;
remindQueue = queue;
}
private void sendMessage(RemindQueue remind) {
//修改发送状态
remindQueueService.updateRemindQueueStatus(remind.getQueueId());//这里在子线程无法获取到DbContext,怎样才能在这里使用主线程注入的service实例?
}
@Override
public void run() {
try {
sendMessage(remindQueue);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}