|
|
@@ -1301,13 +1301,16 @@ public class LiveWatchUserServiceImpl implements ILiveWatchUserService {
|
|
|
return 0L;
|
|
|
}
|
|
|
try {
|
|
|
- long liveDuration = safeOnlineSeconds(baseMapper.selectByUniqueIndex(liveId, userId, 1, 0));
|
|
|
- long replayDuration = safeOnlineSeconds(baseMapper.selectByUniqueIndex(liveId, userId, 0, 1));
|
|
|
- long totalDuration = liveDuration + replayDuration;
|
|
|
-
|
|
|
- log.debug("查询总观看时长: liveId={}, userId={}, liveDuration={}, replayDuration={}, total={}",
|
|
|
- liveId, userId, liveDuration, replayDuration, totalDuration);
|
|
|
-
|
|
|
+ Map<String, Object> params = new HashMap<>();
|
|
|
+ params.put("liveId", liveId);
|
|
|
+ params.put("userId", userId);
|
|
|
+ List<LiveWatchUser> records = baseMapper.selectUserByLiveIdAndUserId(params);
|
|
|
+ if (records == null || records.isEmpty()) {
|
|
|
+ return 0L;
|
|
|
+ }
|
|
|
+ long totalDuration = records.stream().mapToLong(LiveWatchUserServiceImpl::safeOnlineSeconds).sum();
|
|
|
+ log.debug("查询总观看时长: liveId={}, userId={}, recordCount={}, total={}",
|
|
|
+ liveId, userId, records.size(), totalDuration);
|
|
|
return totalDuration;
|
|
|
} catch (Exception e) {
|
|
|
log.error("查询总观看时长失败: liveId={}, userId={}", liveId, userId, e);
|
|
|
@@ -1324,19 +1327,34 @@ public class LiveWatchUserServiceImpl implements ILiveWatchUserService {
|
|
|
|
|
|
@Override
|
|
|
public Long getUserWatchDuration(Long liveId, Long userId) {
|
|
|
- Long total = getTotalWatchDuration(liveId, userId);
|
|
|
- long dbDuration = total != null ? total : 0L;
|
|
|
+ long duration = safeLong(getTotalWatchDuration(liveId, userId));
|
|
|
+ try {
|
|
|
+ String entryTimeKey = String.format(USER_ENTRY_TIME_KEY, liveId, userId);
|
|
|
+ Long entryTime = redisCache.getCacheObject(entryTimeKey);
|
|
|
+ if (entryTime != null) {
|
|
|
+ long sessionSeconds = (System.currentTimeMillis() - entryTime) / 1000;
|
|
|
+ if (sessionSeconds > 0) {
|
|
|
+ duration += sessionSeconds;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.debug("读取 Redis 进入时间失败: liveId={}, userId={}", liveId, userId, e);
|
|
|
+ }
|
|
|
try {
|
|
|
String hashKey = "live:watch:duration:hash:" + liveId;
|
|
|
Object redisValue = redisCache.hashGet(hashKey, String.valueOf(userId));
|
|
|
if (redisValue != null) {
|
|
|
long redisDuration = Long.parseLong(redisValue.toString());
|
|
|
- return Math.max(dbDuration, redisDuration);
|
|
|
+ duration = Math.max(duration, redisDuration);
|
|
|
}
|
|
|
} catch (Exception e) {
|
|
|
log.debug("读取 Redis 观看时长失败: liveId={}, userId={}", liveId, userId, e);
|
|
|
}
|
|
|
- return dbDuration;
|
|
|
+ return duration;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static long safeLong(Long value) {
|
|
|
+ return value != null ? value : 0L;
|
|
|
}
|
|
|
|
|
|
}
|