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

springboot项目Redis统计在线用户

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 {

    @Bean
    public 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";

    @Autowired
    private 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 {

    @Autowired
    private 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.kler.cn/a/532330.html

相关文章:

  • 电控---中断
  • 力扣 121. 买卖股票的最佳时机
  • EF Core与ASP.NET Core的集成
  • 【数据分析】案例04:豆瓣电影Top250的数据分析与Web网页可视化(numpy+pandas+matplotlib+flask)
  • 【memgpt】letta 课程1/2:从头实现一个自我编辑、记忆和多步骤推理的代理
  • 恢复二叉搜索树(99)
  • IFeatureWorkspace.CreateFeatureClass(),报错对COM组件的调用返回了错误 HRESULT E_FAIL
  • intra-mart框架学习笔记:如何找到框架自带页面
  • ComfyUI工作流 参考图像生成人像手办(SDXL版)
  • Nginx的路径匹配规则 笔记250203
  • python渗透开发 高阶段位之 waf绕过sql注入 sqlmap --temper模块开发以及框架逻辑修改 以及解释Temper是什么?
  • Elasticsearch Kibana的下载与安装
  • 关于kamailio重启后无法启动,chatgpt给出的解决方案
  • 排序算法--堆排序
  • C++多线程编程——基于策略模式、单例模式和简单工厂模式的可扩展智能析构线程
  • http请求中的headers和body内容设置
  • 毕业设计:基于深度学习的高压线周边障碍物自动识别与监测系统
  • 如可安装部署haproxy+keeyalived高可用集群
  • 【Numpy核心编程攻略:Python数据处理、分析详解与科学计算】2.23 稀疏矩阵:CSR格式的存储与运算
  • fiddler笔记
  • 基于Flask的抖音用户浏览行为分析系统的设计与实现
  • RocketMQ实战—3.基于RocketMQ升级订单系统架构
  • Rust 中的模块系统:控制作用域与私有性
  • ThreadLocal使用和原理
  • 【Unity2D 2022:UI】创建滚动视图
  • CTFHub信息泄露PHPINFO