帮助中心/最新通知

质量为本、客户为根、勇于拼搏、务实创新

< 返回文章列表

【服务器相关】基于Redis实现抽奖功能及问题小结

发表时间:2025-09-24 16:09:00 小编:主机乐-Yutio

1、分析

  • 公司年底要做年会所有的员工都要参与抽奖的环节
  • 平台的产品要进行抽奖活动

这个时候我们可以利用redis中的set集合中的spop来实现。

特征:抽奖成功的人会自动从集合中删除,即获取到奖品的人不再继续参与抽奖。

spop命令:随机返回元素,元素从集合中删除该元素

2、初始化名单数据


package com.example.service;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Service;import javax.annotation.PostConstruct;import java.util.ArrayList;import java.util.List;/** * @Auther: 长颈鹿 * @Date: 2021/08/21/14:09 * @Description: */@Service@Slf4jpublic class SpopRandomSetService {@Autowiredprivate RedisTemplate redisTemplate;private static final String SPOP_USER_SETS = "pop:user:set";// 把所有员工全部添加到集合列表中@PostConstructpublic void initData(){log.info("初始化奖品等级信息...");// 判断集合是否已经存在boolean flag = this.redisTemplate.hasKey(SPOP_USER_SETS);// 防止作弊if (!flag) {// 获取所有员工的信息List<Integer> initDataList = initDataList();// 把员工信息写入到redis中 sadd key datainitDataList.forEach(data -> this.redisTemplate.opsForSet().add(SPOP_USER_SETS, data));}}// 模拟100用户抽奖private List<Integer> initDataList() {// todo : 从数据库里面来,把公司里面所有的员工从数据表中全部查询出来List<Integer> listData = new ArrayList<>();for (int i = 0; i < 100; i++) {listData.add(i + 1);}return listData;}}

3、具体抽奖方法


// 随机抽取用户public int start(){return (int)redisTemplate.opsForSet().pop(SPOP_USER_SETS);}

4、抽奖接口测试


package com.example.controller;import com.example.service.SpopRandomSetService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController;/** * @Auther: 长颈鹿 * @Date: 2021/08/21/14:13 * @Description: 抽奖接口测试 */@RestControllerpublic class SpopRandomSetController {@Autowiredprivate SpopRandomSetService spopRandomSetService;@PostMapping("/sPop/random/user")public int start() {return spopRandomSetService.start();}}

5、小结


# 查询集合成员smembers pop:user:Set# 查询集合的长度变化scard pop:user:Set

spop:随机从集合取出一个元素返回,并且从集合中删除该元素。

到此这篇关于基于Redis实现抽奖功能的文章就介绍到这了,更多相关Redis实现抽奖内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


联系我们
返回顶部