首页 > 编程语言 > 基于Redis实现抽奖功能及问题小结
2022
05-20

基于Redis实现抽奖功能及问题小结

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
@Slf4j
public class SpopRandomSetService {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String SPOP_USER_SETS = "pop:user:set";

    // 把所有员工全部添加到集合列表中
    @PostConstruct
    public void initData(){
        log.info("初始化奖品等级信息...");
        // 判断集合是否已经存在
        boolean flag = this.redisTemplate.hasKey(SPOP_USER_SETS);
        // 防止作弊
        if (!flag) {
            // 获取所有员工的信息
            List<Integer> initDataList = initDataList();
            // 把员工信息写入到redis中 sadd key data
            initDataList.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: 抽奖接口测试
 */
@RestController
public class SpopRandomSetController {

    @Autowired
    private SpopRandomSetService spopRandomSetService;

    @PostMapping("/sPop/random/user")
    public int start() {
        return spopRandomSetService.start();
    }

}

5、小结

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

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

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

编程技巧