|
|
@ -70,33 +70,33 @@ public class VoteServiceImpl implements VoteService { |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
// 2. 增加候选人的投票数(Hash 表和 ZSet 同步更新) |
|
|
|
// 3. 增加候选人的投票数(Hash 表和 ZSet 同步更新) |
|
|
|
String candidateKey = "candidate:" + candidateJwcode; |
|
|
|
|
|
|
|
// 使用 Redis 的 Hash 增加候选人投票数 |
|
|
|
// 4.使用 Redis 的 Hash 增加候选人投票数 |
|
|
|
redisTemplate.opsForHash().increment(candidateKey, "votes", 1); |
|
|
|
|
|
|
|
// 使用 Redis 的 ZSet 增加候选人投票数 |
|
|
|
// 5.使用 Redis 的 ZSet 增加候选人投票数 |
|
|
|
redisTemplate.opsForZSet().incrementScore("candidate:votes", candidateJwcode, 1); |
|
|
|
|
|
|
|
// 6. 更新 Redis 中的投票次数 |
|
|
|
redisTemplate.opsForValue().increment(redisKey, 1); |
|
|
|
// 设置 Redis 键的过期时间为当天的23:59:59 |
|
|
|
// 7.设置 Redis 键的过期时间为当天的23:59:59 |
|
|
|
LocalDateTime now = LocalDateTime.now(); |
|
|
|
LocalDateTime endOfDay = now.toLocalDate().atTime(23, 59, 59); |
|
|
|
long secondsUntilEndOfDay = Duration.between(now, endOfDay).getSeconds(); |
|
|
|
redisTemplate.expire(redisKey, secondsUntilEndOfDay, TimeUnit.SECONDS); |
|
|
|
//更新投票重复键 |
|
|
|
//8.更新投票重复键 |
|
|
|
stringRedisTemplate.opsForValue().set(voteStatusKey, "true", secondsUntilEndOfDay, TimeUnit.SECONDS); |
|
|
|
//打印剩余长时间过期 |
|
|
|
//9.控制台打印剩余长时间过期 |
|
|
|
System.out.println("Redis键" + redisKey + "将在" + secondsUntilEndOfDay + "秒后过期。"); |
|
|
|
System.out.println("Redis键" + voteStatusKey + "将在" + secondsUntilEndOfDay + "秒后过期。"); |
|
|
|
|
|
|
|
//将投票请求发送到 Kafka 消息队列 |
|
|
|
//10.将投票请求发送到 Kafka 消息队列 |
|
|
|
voteProducer.sendVoteMessage(new VoteMessage(voterJwcode, |
|
|
|
candidateJwcode, voterName, |
|
|
|
Timestamp.valueOf(LocalDateTime.now()).toString())); |
|
|
|
return 2-voteCountToday; |
|
|
|
return dailyVoteLimit - voteCountToday - 1; |
|
|
|
} |
|
|
|
|
|
|
|
//获取所有候选人 |
|
|
@ -117,21 +117,25 @@ public class VoteServiceImpl implements VoteService { |
|
|
|
candidateList.add(candidate); |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
// 插入投票记录,为 List 插入是否投过票的状态 |
|
|
|
for (Candidate candidate : candidateList) { |
|
|
|
List<Voter> voters = voterMapper.countVotesToday(voterJwcode); |
|
|
|
for (Voter voter : voters) { |
|
|
|
if (voter.getCandidateJwCode().equals(candidate.getJwCode())) { |
|
|
|
//从redis查询该用户投票状态 |
|
|
|
String voteStatusKey = "vote_status:" + voterJwcode + ":"; |
|
|
|
//获取stringRedisTemplate的所有键值 |
|
|
|
Set<String> redisCandidateJwCode = stringRedisTemplate.keys(voteStatusKey + "*"); |
|
|
|
//提取最后5位 |
|
|
|
if (redisCandidateJwCode != null) { |
|
|
|
for (String redisKey : redisCandidateJwCode) { |
|
|
|
String candidateJwCode = redisKey.substring(redisKey.length() - 5); |
|
|
|
if (candidate.getJwCode().equals(candidateJwCode)) { |
|
|
|
candidate.setVoted(true); |
|
|
|
break; |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
return candidateList; |
|
|
|
} |
|
|
|
|
|
|
|
//获取候选人被投票记录 |
|
|
|
@Override |
|
|
|
public List<Voter> getVotesByCandidate(String candidateJwcode) { |
|
|
|