79.安心技术梳理 - 团队合作开发常见影响代码性能的注意点,干货

影响代码性能的点,仅供参考

1.防止N+1查询,循环里面套查询(外部查询接口)/查询多条数据循环请求补充其他数据(提供批量服务/并发执行解决)

2.数据库查询频繁的固定内容,增加缓存逻辑,防止并发下大量查询数据库操作

3.涉及到数据库更新操作,避免在查询业务涉及更新操作(增加可读性),库的更新和查询尽量区分开

4.定义传参对象/传递对象,对象中字段有互斥关系的,尽量拆分两个对象定义,增加可读性

事例:

1.N+1影响性能,单个循环查询消耗时间会翻倍,影响性能

public List<ActInfo> getActInfo(List<Long> actIds){
        if(CollectionUtils.isEmpty(actIds)){
            return null;
        }
        List<ActInfo> list = actIds.stream().map(a->{
            //1.actId查询活动信息,请求actService
            ActInfo actInfo = actService.getActInfo(a);
            //2.校验活动中风控信息,请求riskService
            return actInfo;
        }).collect(Collectors.toList());
        return list;
    }

2.并发频繁请求固定数据到数据库

public Result<CacheActDTO> getActById(Long actId) {
        //查询缓存
        CacheActDTO cacheActDTO = getActFromCache(actId);
        //查询数据库
        if (null == cacheActDTO || null == cacheActDTO.getId()) {
            //防止大量并发查询操作
            synchronized (actId) {
                cacheActDTO = getActFromCache(actId);
                if (null != cacheActDTO && null != cacheActDTO.getId()) {
                    return Result.of(cacheActDTO);
                }
                cacheActDTO = cocoonActService.getActFromDB(actId);
                //入缓存
                if (!setActIntoCache(cacheActDTO)) {
                    LogUtil.error("[getActById]-failed to set activity info into cache. actId={}.", actId);
                }
            }
        }
        return Result.of(cacheActDTO);
    }

private boolean setActIntoCache(CacheActDTO actDTO) {
        if (null == actDTO || null == actDTO.getId()) {
            return true;
        }
        boolean setResult = true;
        ActRedisCacheKey actRedisCacheKey = RedisCacheKey.actCacheKey();
        String activityCacheKey = actRedisCacheKey.getActivityCacheKey(actDTO.getId());
        try {
            redisClient.setEx(activityCacheKey, JSON.toJSONString(actDTO), Time);
        } catch (Exception e) {
            setResult = false;
        }
        return setResult;
    }

private CacheActDTO getActFromCache(Long actId) {
        String activityCacheKey = RedisCacheKey.actCacheKey().getActivityCacheKey(actId);
        try {
            String cacheStr = redisClient.get(activityCacheKey);
            return com.jd.fastjson.JSON.parseObject(cacheStr, CacheActDTO.class);
        } catch (Exception e) {
        }
        return null;
    }

3.查询中避免有更新操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值