系统场景-统计用户在线时长

系统场景-统计用户在线时长

方案

使用心跳,如果3分钟没有接收到心跳,则认为用户离线

技术栈

redis zset特性

核心逻辑:

  • 用户调用 login, 将用户登陆时间记录 LOGIN_KEY
  • 用户端启用心跳 heart 记录在HEART_KEY
  • 服务器端起轮询任务
    • 通过 zset.rangeByScore 查询3分钟以前数据
    • 取出用户最新心跳时间(可能在3分钟内再次有了心跳,所以要取最新的)
    • 计算最后心跳时间和当前时间间隔,如果超过3分钟,则为离线
    • 如果离线,调用 logout,并计算用户时长,将用户时长记录在 ONLINE_KEY
  • 如果用户主动调用 logout, 则用户时长=当前时间-用户登陆时间

实现

@Slf4j
@Component
public class OnlineManager {
    /**
     * 登陆key
     */
    private static final String LOGIN_KEY = "online:login";
    /**
     * 在线时长
     */
    private static final String ONLINE_KEY = "online:live";
    /**
     * 心跳
     */
    private static final String HEART_KEY = "online:heart";

    //默认3分钟判定为离线
    private static final Integer DEAD_LINE = 3*60;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    /**
     * 退出
     *
     * @param userId
     */
    public void login(String userId) {
        redisTemplate.opsForHash().putIfAbsent(LOGIN_KEY, userId, System.currentTimeMillis());
    }

    public void loginOut(String userId) {
        Object loginTime = redisTemplate.opsForHash().get(LOGIN_KEY, userId);
        if (loginTime != null) {
            doLogout(userId, loginTime, Instant.now());
            log.info("user {} is logout", userId);
        }
    }

    private void doLogout(String userId, Object loginTime, Instant lastTime) {
        Instant login = Instant.ofEpochMilli(Long.valueOf(loginTime.toString()));
        Duration liveDuration = Duration.between(login, lastTime);
        redisTemplate.opsForZSet().add(ONLINE_KEY, userId, liveDuration.getSeconds());
        //删除登陆记录
        redisTemplate.opsForHash().delete(LOGIN_KEY, userId);
    }


    /**
     * 心跳
     *
     * @param userId
     */
    public void heartBeat(String userId) {
        redisTemplate.opsForZSet().add(HEART_KEY, userId, System.currentTimeMillis());
    }

    /**
     * 获取用户登陆时长
     * @param userId
     * @return
     */
    public Long getOnlineDuration(String userId) {
        Double score = redisTemplate.opsForZSet().score(ONLINE_KEY, userId);
        return score != null ? score.longValue() : null;
    }


    @PostConstruct
    public void offlineJob() {
        //假定3分钟没有心跳就是离线
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            Instant now = Instant.now();
            log.info("online scan: {}",
                    LocalDateTime.ofInstant(now, ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM" +
                            "-dd HH:mm:ss")));
            Instant deadline = now.minusSeconds(DEAD_LINE);
            //查询3分钟以前数据
            Set<Object> userListTmp = redisTemplate.opsForZSet().rangeByScore(HEART_KEY, 0, deadline.toEpochMilli());
            if (CollectionUtils.isEmpty(userListTmp)) {
                log.info("no record");
                return;
            }
            List<String> userList = userListTmp.stream().map(Object::toString).collect(Collectors.toList());
            for (String u : userList) {
                //取出用户最新心跳时间(可能在3分钟内再次有了心跳,所以要取最新的)
                Double score = redisTemplate.opsForZSet().score(HEART_KEY, u);
                if (score != null) {
                    //只要有一条记录,就和当前时间比较,是否超过3分钟
                    Instant lastTime = Instant.ofEpochMilli(score.longValue());
                    Duration duration = Duration.between(lastTime, now);
                    if (duration.getSeconds() >= DEAD_LINE) {
                        //判定为离线
                        //取登陆时间和用户最后一次心跳时间差即为
                        Object loginTime = redisTemplate.opsForHash().get(LOGIN_KEY, u);
                        if (loginTime != null) {
                            doLogout(u, loginTime, lastTime);
                            log.info("user {} is offline", u);
                        } else {
                            //没有登陆记录,有可能通过退出方式
                        }
                        //删除离线用户心跳记录
                        redisTemplate.opsForZSet().remove(HEART_KEY,u);
                    }
                }
            }
        }, 5, 30, TimeUnit.SECONDS);
    }


}

接口

@RestController
public class UserOnlineController {

    @Autowired
    private OnlineManager onlineManager;

    /**
     * 登陆
     * @param userId
     * @return
     */
    @GetMapping("/online/{userId}")
    public String login(@PathVariable("userId") String userId) {
        onlineManager.login(userId);
        return "success";
    }

    /**
     * 退出
     * @param userId
     * @return
     */
    @GetMapping("/online/logout/{userId}")
    public String loginOut(@PathVariable("userId") String userId) {
        onlineManager.loginOut(userId);
        return "success";
    }

    /**
     * 心跳
     * @param userId
     * @return
     */
    @GetMapping("/online/heart/{userId}")
    public String heart(@PathVariable("userId") String userId) {
        onlineManager.heartBeat(userId);
        return "success";
    }


    /**
     * 用户时长
     * @param userId
     * @return
     */
    @GetMapping("/online/duration/{userId}")
    public Long duration(@PathVariable("userId") String userId) {
        return onlineManager.getOnlineDuration(userId);
    }


}

good luck!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值