<p>To optimize the code and improve query speed, you can consider the following suggestions:</p>
<ol>
<li>
<p>Reduce database queries:</p>
<ul>
<li>Instead of querying the updateTimeList and then querying the courseInfos separately, you can use a join query to fetch both the updateTimeList and courseInfos in a single query. This will reduce the number of database queries and improve performance.</li>
<li>Use a single query to fetch the defaultTimes, instead of querying them inside the loop for each defaultTime. This can be done by modifying the queryDefaultTimeByCoachID method to return a list of defaultTimes for a given coachId.</li>
</ul>
</li>
<li>
<p>Use batch operations:</p>
<ul>
<li>Instead of saving each updateTime individually using updateTimeService.saveBatch(updateTimes), you can use batch operations to save all the updateTime objects at once. This will reduce the number of database round trips and improve performance.</li>
</ul>
</li>
<li>
<p>Use parallel streams:</p>
<ul>
<li>When processing the updateTimeList, you can use parallel streams to process the updateTime objects concurrently. This can be done by converting the updateTimeList to a parallel stream using <code>.parallelStream()</code>. However, make sure that the operations performed on each updateTime object are thread-safe.</li>
</ul>
</li>
</ol>
<p>Here's an optimized version of the code with the above suggestions implemented:</p>
<p>@GetMapping(&quot;/queryCourseByCoachIDByDate&quot;)
public Result<Object> queryCourseByCoachIDByDate(Coach coach, String date, HttpServletRequest request) throws ParseException {</p>
<pre><code>// 权限验证
String token = (String) request.getAttribute(&quot;claims_coach&quot;);

if (token == null || &quot;&quot;.equals(token)) {
    throw new RuntimeException(&quot;权限不足!&quot;);
}

if (coach.getCoachId() == null) {
    log.info(&quot;coachId为null&quot;);
    return new Result&lt;&gt;(ResultCode.FAIL);
}

// 转换前端传递日期格式
Date convertedDate = RcqtUtils.getconvertedDate(date);

Map&lt;String, Object&gt; map = new HashMap&lt;&gt;();
// 查询日期对应的数据
List&lt;UpdateTime&gt; updateTimeList = updateTimeService.queryUpdateTimeByDate(coach.getCoachId(), convertedDate);

if (CollectionUtils.isEmpty(updateTimeList)) {
    log.info(&quot;查询当前日期数据为空!&quot;);
    // 查询教练自己设置的默认时间段
    List&lt;DefaultTime&gt; defaultTimes = defaultTimeService.queryDefaultTimeByCoachID(coach.getCoachId());

    if (!defaultTimes.isEmpty()) {
        List&lt;UpdateTime&gt; updateTimes = defaultTimes.stream()
                .filter(defaultTime -&gt; defaultTime.getStartReservationTime() != null &amp;&amp; defaultTime.getEndReservationTime() != null)
                .map(defaultTime -&gt; {
                    UpdateTime updateTime = new UpdateTime();
                    updateTime.setCoachId(coach.getCoachId());
                    updateTime.setProjectType(defaultTime.getProjectType());
                    updateTime.setCourseDate(convertedDate);
                    updateTime.setStartReservationTime(defaultTime.getStartReservationTime());
                    updateTime.setEndReservationTime(defaultTime.getEndReservationTime());
                    updateTime.setMaxReservation(defaultTime.getMaxReservation());
                    updateTime.setCourseStatus(false);// 人数未满
                    updateTime.setCurrentReservation(0);// 当前预约人数0
                    SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;);
                    String currentDate = dateFormat.format(convertedDate);
                    String week = RcqtUtils.getDayOfWeek(currentDate);// 得到当前日期对应周几
                    if (!StringUtils.isEmpty(week)) {
                        updateTime.setIsBreakDate(defaultTime.getRestDay().contains(week));
                    }
                    return updateTime;
                })
                .collect(Collectors.toList());

        // Batch save the updateTimes
        boolean b = updateTimeService.saveBatch(updateTimes);
        if (!b) {
            log.info(&quot;新增失败&quot;);
            return new Result&lt;&gt;(ResultCode.FAIL);
        }
        List&lt;Long&gt; updateTimeIds = updateTimes.stream().map(UpdateTime::getUpdateTimeId).collect(Collectors.toList());

        // Parallel stream to query courseInfos
        List&lt;CourseInfo&gt; courseInfos = courseInfoService.queryCourseByUpdateTimeIds(updateTimeIds);
        Map&lt;Long, List&lt;CarUser&gt;&gt; courseInfoMap = courseInfos.parallelStream()
                .collect(Collectors.groupingByConcurrent(CourseInfo::getUpdateTimeId,
                        Collectors.mapping(courseInfo -&gt; carUserService.queryOneCarUserById(courseInfo.getUserId()), Collectors.toList())));

        updateTimeList = updateTimes.stream()
                .map(updateTime -&gt; {
                    UpdateTimeDto updateTimeDto = new UpdateTimeDto();
                    BeanUtils.copyProperties(updateTime, updateTimeDto);
                    List&lt;CarUser&gt; carUserList = courseInfoMap.get(updateTime.getUpdateTimeId());
                    if (carUserList != null) {
                        updateTimeDto.setCurrentReservation(carUserList.size());// 当前预约人数
                        updateTimeDto.setCarUserList(carUserList);
                        if (carUserList.size() == updateTime.getMaxReservation()) {
                            updateTimeDto.setCourseStatus(true);// 设置课程状态为已满
                        }
                    }
                    if (updateTimeDto.getCourseDate().equals(RcqtUtils.getDay()) &amp;&amp; updateTimeDto.getStartReservationTime() != null) {
                        updateTimeDto.setIsTimeOut(LocalTime.now().isAfter(updateTimeDto.getStartReservationTime().toLocalTime()));
                    }
                    return updateTimeDto;
                })
                .collect(Collectors.toList());
    }
} else {
    List&lt;Long&gt; updateTimeIds = updateTimeList.stream().map(UpdateTime::getUpdateTimeId).collect(Collectors.toList());
    // Parallel stream to query courseInfos
    List&lt;CourseInfo&gt; courseInfos = courseInfoService.queryCourseByUpdateTimeIds(updateTimeIds);
    Map&lt;Long, List&lt;CarUser&gt;&gt; courseInfoMap = courseInfos.parallelStream()
            .collect(Collectors.groupingByConcurrent(CourseInfo::getUpdateTimeId,
                    Collectors.mapping(courseInfo -&gt; carUserService.queryOneCarUserById(courseInfo.getUserId()), Collectors.toList())));

    updateTimeList = updateTimeList.stream()
            .map(updateTime -&gt; {
                UpdateTimeDto updateTimeDto = new UpdateTimeDto();
                BeanUtils.copyProperties(updateTime, updateTimeDto);
                List&lt;CarUser&gt; carUserList = courseInfoMap.get(updateTime.getUpdateTimeId());
                if (carUserList != null) {
                    updateTimeDto.setCurrentReservation(carUserList.size());// 当前预约人数
                    updateTimeDto.setCarUserList(carUserList);
                    if (carUserList.size() == updateTime.getMaxReservation()) {
                        updateTimeDto.setCourseStatus(true);// 设置课程状态为已满
                    }
                }
                if (updateTimeDto.getCourseDate().equals(RcqtUtils.getDay()) &amp;&amp; updateTimeDto.getStartReservationTime() != null) {
                    updateTimeDto.setIsTimeOut(LocalTime.now().isAfter(updateTimeDto.getStartReservationTime().toLocalTime()));
                }
                return updateTimeDto;
            })
            .collect(Collectors.toList());
}

for (UpdateTimeDto updateTimeDto : updateTimeList) {
    if (updateTimeDto.getIsTimeOut() != null &amp;&amp; updateTimeDto.getIsTimeOut()) {
        map.put(&quot;isTimeOutAll&quot;, true);
        break;
    }
}

map.put(&quot;isBreakDate&quot;, updateTimeList.stream().anyMatch(UpdateTime::getIsBreakDate));
map.put(&quot;updateTimeList&quot;, updateTimeList);
log.info(&quot;通过日期查询约课安排成功!&quot;);
return new Result&lt;&gt;(ResultCode.SUCCESS, map);
</code></pre>
GetMappingqueryCourseByCoachIDByDate public ResultObject queryCourseByCoachIDByDateCoach coach String date HttpServletRequest request throws ParseException 权限验证 String token = Strin

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

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