针对项目中性能调优总结有如下几条:

  1. 避免服务间的多次调用,可将多次修改为一次,对于查询业务,如业务不允许则可将业务数据进行缓存(代码或者redis进行缓存)。
  2. 服务间调用对于无需返回并且对数据准确性结果较弱的操作,尝试修改为异步,尽快释放连接。
  3. 修改操作及删除操作条件必须明确,避免单独使用主键,例如加上区划,年度,单位等。
  4. 禁止使用new Runable(), 使用线程必须使用线程池明确最小,最大线程数。
  5. 单次插入数据量特别大,字段特别多,业务的使用量
    具体写法如下图:
    image.png
    image.png
    image.png
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
public void test(List insertList){
SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
try {
    GlaBalanceDao blDao = sqlSession.getMapper(GlaBalanceDao.class);
    insertList.stream().forEach(bal->{
        blDao.insert(bal);
    });
    sqlSession.clearCache();
    sqlSession.commit();
}catch(Exception e){
    throw new RuntimeException(e);
}finally {
    sqlSession.close();
}
}

开启mybatis batch模式源码解析:
image.png
image.png
image.png
image.png
image.png


补充:
可以把批量插入的逻辑提取成工具类

首先定义一个工具类比如:Tool
这里我们使用@Component注解
定义静态量类型是Tool并注入SqlSessionFactory
`
@Autowired
public SqlSessionFactory sqlSessionFactory;
public static Tool tool;
`
使用@PostConstruct初始化方法

@PostConstruct
public void init() {
  tool = this;
  tool.sqlSessionFactory = this.sqlSessionFactory;
}

使用 @FunctionalInterface声明一个函数式接口

@FunctionalInterface
   public interface TwoConsumer<O, T> {
       void accept(O one, T two);
   }

然后使用反射做一个批量插入的方法

 public static <D, E> void batchInsert(Class<D> daoClass, List<E> list, EfmTool.TwoConsumer<D, E> insertFunction) {
        //新建一个SqlSession
        SqlSession sqlSession = tool.sqlSessionFactory.openSession(ExecutorType.BATCH);
        //获取对应的Mapper
        D mapper = sqlSession.getMapper(daoClass);
        try {
            //插入数据
            for (E data : list) {
                JSONUtil.toJsonStr(data);
                insertFunction.accept(mapper, data);
            }
            //清除本地会话缓存
            sqlSession.clearCache();
            //提交
            sqlSession.commit();
        } catch (Exception e) {
            log.error("插入数据异常===>>{}",e);
            //一次事务回滚
            sqlSession.rollback();
            throw e;
        } finally {
            //关闭sqlSession
            sqlSession.close();
        }
    }

然后是使用

Tool.batchInsert(cs.class, list, csDao::insert);

纯洁的麦兜
18 声望4 粉丝

学习使人进步