当前位置: 首页 > news >正文

Spring Boot:运用Redis统计用户在线数量

在Spring Boot里运用Redis统计用户在线数量。

项目依赖与配置

1. 引入依赖

首先,在pom.xml文件中添加Spring Data Redis依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置Redis连接

application.properties中进行Redis连接的配置:

spring.redis.host=localhost
spring.redis.port=6379

方案1:借助Redis Set实现精确统计

1. 创建Redis操作Service

编写一个Redis操作Service,用于处理用户在线状态:

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import java.util.Set;@Service
public class OnlineUserService {private static final String ONLINE_USERS_KEY = "online_users";private final RedisTemplate<String, String> redisTemplate;public OnlineUserService(RedisTemplate<String, String> redisTemplate) {this.redisTemplate = redisTemplate;}// 用户登录public void login(String userId) {redisTemplate.opsForSet().add(ONLINE_USERS_KEY, userId);}// 用户退出public void logout(String userId) {redisTemplate.opsForSet().remove(ONLINE_USERS_KEY, userId);}// 获取在线用户数public Long getOnlineCount() {return redisTemplate.opsForSet().size(ONLINE_USERS_KEY);}// 获取所有在线用户IDpublic Set<String> getOnlineUsers() {return redisTemplate.opsForSet().members(ONLINE_USERS_KEY);}
}
2. 控制器示例

创建一个控制器,用于测试上述功能:

import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/online")
public class OnlineUserController {private final OnlineUserService onlineUserService;public OnlineUserController(OnlineUserService onlineUserService) {this.onlineUserService = onlineUserService;}@PostMapping("/login/{userId}")public String login(@PathVariable String userId) {onlineUserService.login(userId);return userId + " 已登录";}@PostMapping("/logout/{userId}")public String logout(@PathVariable String userId) {onlineUserService.logout(userId);return userId + " 已退出";}@GetMapping("/count")public Long getCount() {return onlineUserService.getOnlineCount();}@GetMapping("/users")public Set<String> getUsers() {return onlineUserService.getOnlineUsers();}
}

方案2:使用Redis Bitmap实现按位存储

1. Bitmap操作Service

创建一个专门用于Bitmap操作的Service:

import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;@Service
public class OnlineUserBitmapService {private static final String ONLINE_USERS_BITMAP_KEY = "online_users_bitmap";private final RedisTemplate<String, Object> redisTemplate;public OnlineUserBitmapService(RedisTemplate<String, Object> redisTemplate) {this.redisTemplate = redisTemplate;}// 用户登录(userId需为Long类型)public void login(Long userId) {redisTemplate.execute((RedisCallback<Boolean>) connection ->connection.setBit(ONLINE_USERS_BITMAP_KEY.getBytes(), userId, true));}// 用户退出public void logout(Long userId) {redisTemplate.execute((RedisCallback<Boolean>) connection ->connection.setBit(ONLINE_USERS_BITMAP_KEY.getBytes(), userId, false));}// 检查用户是否在线public Boolean isOnline(Long userId) {return redisTemplate.execute((RedisCallback<Boolean>) connection ->connection.getBit(ONLINE_USERS_BITMAP_KEY.getBytes(), userId));}// 获取在线用户数public Long getOnlineCount() {return redisTemplate.execute((RedisCallback<Long>) connection ->connection.bitCount(ONLINE_USERS_BITMAP_KEY.getBytes()));}// 统计指定范围内的在线用户数public Long getOnlineCount(long start, long end) {return redisTemplate.execute((RedisCallback<Long>) connection ->connection.bitCount(ONLINE_USERS_BITMAP_KEY.getBytes(), start, end));}
}
2. 控制器示例

创建对应的控制器:

import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/online/bitmap")
public class OnlineUserBitmapController {private final OnlineUserBitmapService onlineUserBitmapService;public OnlineUserBitmapController(OnlineUserBitmapService onlineUserBitmapService) {this.onlineUserBitmapService = onlineUserBitmapService;}@PostMapping("/login/{userId}")public String login(@PathVariable Long userId) {onlineUserBitmapService.login(userId);return userId + " 已登录";}@PostMapping("/logout/{userId}")public String logout(@PathVariable Long userId) {onlineUserBitmapService.logout(userId);return userId + " 已退出";}@GetMapping("/count")public Long getCount() {return onlineUserBitmapService.getOnlineCount();}@GetMapping("/{userId}")public Boolean isOnline(@PathVariable Long userId) {return onlineUserBitmapService.isOnline(userId);}
}

使用建议

1. Set方案的适用场景
  • 当需要精确统计在线用户数量,并且能够获取在线用户列表时,可以使用Set方案。
  • 适合用户规模在百万级别以下的情况,因为Set会存储每个用户的ID。
2. Bitmap方案的适用场景
  • 若用户ID是连续的整数(或者可以映射为连续整数),Bitmap方案会更节省内存。
  • 对于大规模用户(比如亿级)的在线统计,Bitmap方案具有明显优势。
  • 示例中使用Long类型的userId,在实际应用中,你可能需要一个ID映射器,将业务ID转换为连续的整数。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.dtcms.com/a/257396.html

相关文章:

  • 百度AIP:Springboot人脸对比
  • 【钓鱼预警】针对跨境销售投递Tesla间谍木马
  • <tauri><threejs><rust><GUI>基于tauri和threejs,实现一个3D图形浏览程序
  • 初探 Nacos 原理
  • Qt/C++开发监控GB28181系统/rtp解包/jrtplib库的使用/同时支持udp和tcp被动和主动三种方式解包
  • 日志技术-Logback入门程序
  • 初见语音识别(ASR)
  • 通过审计日志分析和摘要利用大型语言模型进行网络攻击检测
  • K8S: etcdserver: too many requests
  • 2025 年前端框架的深度解析与展望
  • 微服务(nacos+myibatis)中如何在一个模块调用多数据库源的一种方案
  • 矩阵阶数(线性代数) vs. 张量维度(深度学习):线性代数与深度学习的基石辨析,再也不会被矩阵阶数给混淆了
  • 对kotti_image项目进行pytest测试操作实践(失败)
  • Camera Sensor接口协议全解析(四)LVDS与SubLVDS接口及协议深度解析
  • 【第二章:机器学习与神经网络概述】03.类算法理论与实践-(1)逻辑回归(Logistic Regression)
  • 108页精品PPT | 大型某著名企业能源行业数字化转型汇报方案能源化工数字化转型
  • Java基础(三):逻辑运算符详解
  • 阿里云Elasticsearch生产环境误删数据恢复指南
  • LabVIEW网络流通信介绍
  • Elasticsearch(ES)与 OpenSearch(OS)
  • 实现 el-table 中键盘方向键导航功能vue2+vue3(类似 Excel)
  • 从0开始学习R语言--Day30--函数型分析
  • Centos 7离线部署Nginx 高效省时
  • uniapp安卓GPIO电平控制
  • Milvus【部署 03】Linux OpenEuler 环境在线+离线安装及卸载
  • 【软考高级系统架构论文】论企业集成架构设计及应用
  • Milvus【工具 01】milvus_cli和可视化工具attu安装使用
  • uniapp vue2多选模糊下拉组件
  • 住宅老年护理软件:市场洞察与发展前景
  • 顶级思维方式——认知篇十一《传习录》笔记