码上敲享录 > mongoDB常见问题解答 > mongoTemplate的findAndModify可以保证数据安全?

mongoTemplate的findAndModify可以保证数据安全?

上一章章节目录下一章 2021-01-25已有1870人阅读 评论(0)

mongoTemplate的findAndModify可以保证数据安全?


解决方法:

我下面开启500个线程高并发修改表accountInfo 对象的中onlinesurveyTotalStore字段,如果结果是3000那么说明findAndModify可以保证数据安全,否则就不能保证。


1.使用平时更新实体类的方法并发更新

ThreadPoolExecutor executor = new ThreadPoolExecutor(500, 1000, 30*1000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>(100000));

Criteria accountWhere = Criteria.where("status").is(1);

 accountWhere.and("userId").is(GetUserInfo.currentUserInfo().getId());

  Query accountQuery = new Query(accountWhere);

       for (int i = 0; i < 3000; i++) {

           

           executor.execute(new Runnable() {//多线程处理任务

               @Override

               public void run() {

                 AccountInfo andModify = template.findOne(accountQuery, AccountInfo.class);

           andModify.setOnlinesurveyTotalStore(andModify.getOnlinesurveyTotalStore() + 1);

           template.save(andModify);

               }

           });


       }


结果:数据库中onlinesurveyTotalStore的值是11,可以知道高并发时使用save更新数据时是不安全的。


2.使用findAndModify方法并发更新

ThreadPoolExecutor executor = new ThreadPoolExecutor(500, 1000, 30*1000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>(100000));

Criteria accountWhere = Criteria.where("status").is(1);

 accountWhere.and("userId").is(GetUserInfo.currentUserInfo().getId());

  Query accountQuery = new Query(accountWhere);

       for (int i = 0; i < 3000; i++) {

           

           executor.execute(new Runnable() {//多线程处理任务

               @Override

               public void run() {

                  Update update = new Update();

                   update.inc("onlinesurveyTotalStore", 1);

                   template.findAndModify(accountQuery, update, AccountInfo.class);

               }

           });


       }


结果:数据库中onlinesurveyTotalStore的值是3000,可以知道高并发时使用findAndModify更新数据时安全的,一般用来扣费。


向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交