@
目录
提示:本文仅供学习交流,请勿用于非法活动!
<font color="#999AAA"> 一、原来代码
如下,我们将拷贝100万条数据到MongoDB中。
<font color="#999AAA">- public void copyCartToMongo() {
- List<Cart> carts = cartMapper.selectAll();
- if(carts.size() >0 ){
- cartMongoService.saveCartList(carts);
- }
- }
复制代码 二、改进后代码
- public void copyCartToMongoByThread() {
- // 1.我们先将批量查询及拷贝的数据分批
- EntityWrapper<Cart> wrapper = SQLHelper.buildEmptyWrapper(Cart.class);
- long count = cartMapper.selectCount(SQLHelper.build(Cart.class).geEntityWrapper());
- int preCount = 100;
- int operateCount = 0;
- int num = operateCount = (int)count / preCount;
- if(count % preCount == 0){
- operateCount = num;
- }else {
- operateCount = num + 1;
- }
- for(int i=0;i<operateCount;i++){
- logger.info("保存或更新第"+(i+1)*preCount+"条数据");
- Page<Cart> page = new Page<>(i,preCount);
- List<Cart> cartList = cartMapper.selectPage(page, wrapper);
- // 2.通过多线程、线程池(其他替换即可)
- this.copyCartToMongoThread(cartList);
- }
- }
复制代码 2.使用Runnable接口
代码如下:
<font color="#999AAA">- public void copyCartToMongoThread(List<Cart> cartList){
- final CountDownLatch latch = new CountDownLatch(cartList.size());
- try{
- for(Cart cart:cartList){
- Thread thread = new Thread(() -> {
- cartMongoService.saveCart(cart);
- latch.countDown();
- });
- thread.start();
- }
- latch.await();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
复制代码 3.使用线程池
代码如下:
<font color="#999AAA">- public void copyCartToMongoThread(List<Cart> cartList){
- final CountDownLatch latch = new CountDownLatch(cartList.size());
- try {
- for (Cart cart:cartList){
- new Thread(new Runnable() {
- @Override
- public void run() {
- cartMongoService.saveCart(cart);
- latch.countDown();
- }
- }).start();
- }
- latch.await();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
复制代码 |