springboot项目Redis统计在线用户

ops/2025/2/5 13:47:00/

SEO Meta Description: 了解如何在Spring Boot项目中使用Redis实现在线用户统计,提供详细的实现步骤和代码示例,帮助您高效管理在线用户。

介绍

在现代Web应用中,统计在线用户是一个常见需求。通过Redis可以高效地管理和统计在线用户。本文将详细介绍如何在Spring Boot项目中使用Redis统计在线用户,包括配置Redis、实现用户登录和注销逻辑,以及统计在线用户数。

环境准备

在开始之前,请确保您的开发环境中已经安装并配置了以下组件:

  • Java 8或以上版本
  • Spring Boot
  • Redis服务器
  • Maven或Gradle

配置Redis

添加依赖

在 pom.xml中添加Redis和Spring Data Redis的依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
​

配置Redis连接

在 application.properties文件中配置Redis连接信息:

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=your_password # 如果有设置密码
​

实现用户在线统计

Redis配置类

创建一个Redis配置类,配置RedisTemplate:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());return template;}
}
​

用户服务类

创建一个服务类,处理用户登录、注销和在线用户统计逻辑:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import java.util.Set;
import java.util.concurrent.TimeUnit;@Service
public class UserService {private static final String ONLINE_USERS_KEY = "onlineUsers";@Autowiredprivate RedisTemplate<String, Object> redisTemplate;public void loginUser(String userId) {redisTemplate.opsForSet().add(ONLINE_USERS_KEY, userId);redisTemplate.expire(ONLINE_USERS_KEY, 30, TimeUnit.MINUTES); // 设置过期时间}public void logoutUser(String userId) {redisTemplate.opsForSet().remove(ONLINE_USERS_KEY, userId);}public Set<Object> getOnlineUsers() {return redisTemplate.opsForSet().members(ONLINE_USERS_KEY);}public Long getOnlineUserCount() {return redisTemplate.opsForSet().size(ONLINE_USERS_KEY);}
}
​

控制器类

创建一个控制器类,处理前端请求:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.Set;@RestController
@RequestMapping("/users")
public class UserController {@Autowiredprivate UserService userService;@PostMapping("/login")public String loginUser(@RequestParam String userId) {userService.loginUser(userId);return "User logged in: " + userId;}@PostMapping("/logout")public String logoutUser(@RequestParam String userId) {userService.logoutUser(userId);return "User logged out: " + userId;}@GetMapping("/online")public Set<Object> getOnlineUsers() {return userService.getOnlineUsers();}@GetMapping("/online/count")public Long getOnlineUserCount() {return userService.getOnlineUserCount();}
}
​

运行和测试

启动应用

启动Spring Boot应用,确保Redis服务器正在运行。

测试API

使用Postman或其他API测试工具,测试以下API:

  1. 登录用户

    • URL: POST http://localhost:8080/users/login
    • 参数: userId
    {"userId": "user1"
    }
    ​
    
  2. 注销用户

    • URL: POST http://localhost:8080/users/logout
    • 参数: userId
    {"userId": "user1"
    }
    ​
    
  3. 获取在线用户列表

    • URL: GET http://localhost:8080/users/online
  4. 获取在线用户数量

    • URL: GET http://localhost:8080/users/online/count

http://www.ppmy.cn/ops/155883.html

相关文章

低空经济火热,大载重物流运输无人机技术详解

低空经济是指在3000米以下的低空空域为依托&#xff0c;以各种有人和无人驾驶航空器的低空飞行活动为牵引&#xff0c;辐射带动相关领域融合发展的综合性经济形态。随着技术的发展和政策的支持&#xff0c;低空经济已经成为一个热门领域&#xff0c;特别是在物流运输方面&#…

【Blazor学习笔记】.NET Blazor学习笔记

我是大标题 我学习Blazor的顺序是基于Blazor University&#xff0c;然后实际内容不完全基于它&#xff0c;因为它的例子还是基于.NET Core 3.1做的&#xff0c;距离现在很遥远了。 截至本文撰写的时间&#xff0c;2025年&#xff0c;最新的.NET是.NET9了都&#xff0c;可能1…

Linux:指令大全(二)

cat命令 在linux中&#xff0c;我们是没办法用鼠标进行翻页阅读的&#xff0c;如果我们想要阅读文件的话&#xff0c;则需要用到cat指令。 语法&#xff1a;cat 选项 文件 功能&#xff1a;查看文件的内容 常用选项&#xff1a; -b 对非空行编号-n 对所有行编号-s 禁止重复的…

【贪心算法篇】:“贪心”之旅--算法练习题中的智慧与策略(三)

✨感谢您阅读本篇文章&#xff0c;文章内容是个人学习笔记的整理&#xff0c;如果哪里有误的话还请您指正噢✨ ✨ 个人主页&#xff1a;余辉zmh–CSDN博客 ✨ 文章所属专栏&#xff1a;贪心算法篇–CSDN博客 文章目录 前言例题1.最优除法2.跳跃游戏23.跳跃游戏14.加油站5.单调递…

每日 Java 面试题分享【第 19 天】

欢迎来到每日 Java 面试题分享栏目&#xff01; 订阅专栏&#xff0c;不错过每一天的练习 今日分享 3 道面试题目&#xff01; 评论区复述一遍印象更深刻噢~ 目录 问题一&#xff1a;Java Object 类中有什么方法&#xff0c;有什么作用&#xff1f;问题二&#xff1a;Java …

lstm代码解析1.2

在使用 LSTM&#xff08;长短期记忆网络&#xff09;进行训练时&#xff0c;model.fit 方法的输入数据 X 和目标数据 y 的形状要求是不同的。具体来说&#xff1a; 1. 输入数据 X 的形状 LSTM 层期望输入数据 X 是三维张量&#xff0c;形状为 (samples, timesteps, features)…

leetcode——二叉树展开为链表(java)

给你二叉树的根结点 root &#xff0c;请你将它展开为一个单链表&#xff1a; 展开后的单链表应该同样使用 TreeNode &#xff0c;其中 right 子指针指向链表中下一个结点&#xff0c;而左子指针始终为 null 。 展开后的单链表应该与二叉树 先序遍历 顺序相同。 示例 1&#…

如何学习Java后端开发

文章目录 一、Java 语言基础二、数据库与持久层三、Web 开发基础四、主流框架与生态五、分布式与高并发六、运维与部署七、项目实战八、持续学习与提升总结路线图 学习 Java 后端开发需要系统性地掌握多个技术领域&#xff0c;从基础到进阶逐步深入。以下是一个详细的学习路线和…