现象:

WriteResult res = mongoTemplate.updateFirst(query, updateObj, "ServerToAgentReq_SMS");

获取res.getN()返回值时,发现偶尔情况下该返回值为0,表示该更新操作没有更新到任何数据。并且如果是多线程并发更新,失败几率大大提高。

官网表示不能保证更新操作的成功性....

方案:

一次失败后,另起线程多次重试。

 

 private ThreadPoolExecutor exec = new ThreadPoolExecutor(2, 10, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10), new ThreadPoolExecutor.CallerRunsPolicy());

主要代码: 
WriteResult res = mongoTemplate.updateFirst(query, updateObj, "ServerToAgentReq_SMS");
            //如果更新失败,进入其他线程重试更新
            if (res.getN() == 0) {
                exec.execute(new Runnable() {
                    @Override
                    public void run() {
                        int num = 0;
                        WriteResult res = mongoTemplate.updateFirst(query, updateObj, "ServerToAgentReq_SMS");
                        while (res.getN() == 0 && num < 100) {
                            res = mongoTemplate.updateFirst(query, updateObj, "ServerToAgentReq_SMS");
                            num++;
                            try {
                                Thread.sleep(300);
                            } catch (InterruptedException e) {
                                logger.error("响应更新失败{}", e);
                            }
                        }
                        if (res.getN() == 0) {
                            logger.error("响应更新失败!!!gwMsgId:{},masMsgId:{}", gwMsgId, masMsgId);
                        }
                    }
                });

如此失败率,大大减少。

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-29
  • 2022-12-23
  • 2021-11-05
  • 2021-10-24
  • 2021-12-04
  • 2021-09-08
猜你喜欢
  • 2022-02-19
  • 2021-09-01
  • 2022-12-23
  • 2021-10-17
  • 2021-04-24
  • 2021-11-02
  • 2022-12-23
相关资源
相似解决方案