基于Redis實現(xiàn)抽獎功能及問題小結
更新時間:2021年08月23日 10:48:04 作者:南宮拾壹
這篇文章主要介紹了基于Redis實現(xiàn)抽獎功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
1、分析
- 公司年底要做年會所有的員工都要參與抽獎的環(huán)節(jié)
- 平臺的產(chǎn)品要進行抽獎活動
這個時候我們可以利用redis中的set集合中的spop來實現(xiàn)。
特征:抽獎成功的人會自動從集合中刪除,即獲取到獎品的人不再繼續(xù)參與抽獎。
spop命令:隨機返回元素,元素從集合中刪除該元素
2、初始化名單數(shù)據(jù)
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("初始化獎品等級信息..."); // 判斷集合是否已經(jīng)存在 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 : 從數(shù)據(jù)庫里面來,把公司里面所有的員工從數(shù)據(jù)表中全部查詢出來 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實現(xiàn)抽獎功能的文章就介紹到這了,更多相關Redis實現(xiàn)抽獎內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關文章
Redis教程(二):String數(shù)據(jù)類型
這篇文章主要介紹了Redis教程(二):String數(shù)據(jù)類型,本文講解了String數(shù)據(jù)類型概述、相關命令列表、命令使用示例三部分內(nèi)容,需要的朋友可以參考下2015-04-04基于Redis?zSet實現(xiàn)滑動窗口對短信進行防刷限流的問題
這篇文章主要介紹了基于Redis?zSet實現(xiàn)滑動窗口對短信進行防刷限流,主要針對目前線上短信被腳本惡意盜刷的情況,用Redis實現(xiàn)滑動窗口限流,本文通過實例代碼給大家介紹的非常詳細,需要的朋友參考下吧2022-02-02淺析Redis中String數(shù)據(jù)類型及其底層編碼
這篇文章主要介紹?Redis?中?String?數(shù)據(jù)類型及其底層編碼,文中有詳細的代碼示例,對大家的工作及學習有一定的幫助,需要的朋友可以參考下2023-05-05