要提升代码速度,可以采取以下几个方案:

  1. 避免不必要的数据转换和重复查询:在代码中有多次进行数据转换和查询数据库的地方,可以考虑减少转换和查询的次数。例如,在代码中多次使用specificRegularService.queryOneSpecificRegularByID()方法查询具体规则信息,可以将查询结果缓存起来,避免重复查询。

  2. 使用批量操作:在代码中使用了批量修改具体规则的方法specificRegularService.updateBatchById(),可以尝试将批量操作的数量适当增加,减少单个操作的次数,从而提高效率。

  3. 使用多线程或异步处理:对于一些耗时的操作,可以考虑使用多线程或异步处理的方式来提高代码执行的速度。例如,在具体规则批量修改成功后,可以将通知游戏端修改的具体规则的操作放在一个单独的线程或异步任务中处理,不影响主线程的执行。

下面是相应的代码修改示例:

@PostMapping("/updateSpecificRegulars")
public Result<Object> updateSpecificRegulars(@RequestBody Map<String, Object> params, HttpServletRequest request) {
    // 省略权限验证和日志打印部分

    List<SpecificRegular> specificRegulars = getSpecificRegularsFromParams(params);

    // 省略验证码验证部分
    
    if (!CollectionUtils.isEmpty(specificRegulars)) {
        List<SpecificRegular> specificRegularList = specificRegulars.stream()
                .map(specificRegular -> {
                    SpecificRegular specificRegularMy = getSpecificRegularFromCacheOrDB(specificRegular.getSpecificRegularId());
                    // 省略具体规则修改逻辑部分
                    return specificRegularMy;
                })
                .collect(Collectors.toList());
        
        boolean batchUpdate = specificRegularService.updateBatchById(specificRegularList);// 修改具体规则
        if (batchUpdate) {
            log.info("具体规则批量修改成功!");
            // 异步通知游戏端修改的具体规则
            CompletableFuture.runAsync(() -> {
                springToGameService.reloadUpdateSpecificRegular(specificRegularList);
            });
            return new Result<>(ResultCode.SUCCESS);
        } else {
            log.error("具体规则批量修改失败!");
            return new Result<>(ResultCode.FAIL);
        }
    } else {
        log.error("前端传回集合为空");
        return new Result<>(ResultCode.FAIL);
    }
}

// 从请求参数中获取具体规则列表
private List<SpecificRegular> getSpecificRegularsFromParams(Map<String, Object> params) {
    JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(params));
    JSONArray jsonArray = jsonObject.getJSONArray("specificRegular");
    return jsonArray.toJavaList(SpecificRegular.class);
}

// 从缓存或数据库中获取具体规则信息
private SpecificRegular getSpecificRegularFromCacheOrDB(Long specificRegularId) {
    SpecificRegular specificRegular = redisTemplateByObject.opsForValue().get("SpecificRegularId" + specificRegularId);
    if (specificRegular == null) {
        specificRegular = specificRegularService.queryOneSpecificRegularByID(specificRegularId);
        redisTemplateByObject.opsForValue().set("SpecificRegularId" + specificRegularId, specificRegular);// 缓存
    }
    return specificRegular;
}

通过以上优化,可以减少不必要的数据转换和重复查询,同时将通知游戏端修改的具体规则的操作放在异步任务中处理,从而提高代码的执行速度

2批量修改具体规则信息-只修改规则 PostMappingupdateSpecificRegulars public ResultObject updateSpecificRegularsRequestBody MapString Object params HttpServletRequest request 权限验证 String token = St

原文地址: http://www.cveoy.top/t/topic/iLXO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录