首页 新闻 会员 周边 捐助

spring中注入的service实例,如何在线程池中使用

0
[待解决问题]
@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();
            }
        }
    }
}
ludi的主页 ludi | 初学一级 | 园豆:5
提问于:2018-02-07 12:08
< >
分享
所有回答(0)
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册