這個時候我們可以利用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) { // 獲取所有員工的信息 ListInteger> initDataList = initDataList(); // 把員工信息寫入到redis中 sadd key data initDataList.forEach(data -> this.redisTemplate.opsForSet().add(SPOP_USER_SETS, data)); } } // 模擬100用戶抽獎 private ListInteger> initDataList() { // todo : 從數(shù)據(jù)庫里面來,把公司里面所有的員工從數(shù)據(jù)表中全部查詢出來 ListInteger> 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、小結(jié)
# 查詢集合成員 smembers pop:user:Set # 查詢集合的長度變化 scard pop:user:Set
spop:隨機從集合取出一個元素返回,并且從集合中刪除該元素。
到此這篇關(guān)于基于Redis實現(xiàn)抽獎功能的文章就介紹到這了,更多相關(guān)Redis實現(xiàn)抽獎內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!