|
|
@ -24,6 +24,8 @@ import java.util.List; |
|
|
|
import java.util.Set; |
|
|
|
import java.util.concurrent.TimeUnit; |
|
|
|
|
|
|
|
import static com.lh.bean.RedisKey.*; |
|
|
|
|
|
|
|
@Service |
|
|
|
public class VoteServiceImpl implements VoteService { |
|
|
|
|
|
|
@ -67,7 +69,7 @@ public class VoteServiceImpl implements VoteService { |
|
|
|
throw new MyException("候选人不存在"); |
|
|
|
} |
|
|
|
|
|
|
|
String redisKey = "vote_count:" + voterJwcode + ":" + LocalDateTime.now().toLocalDate(); |
|
|
|
String redisKey = CACHE_KEY_VOTE_COUNT + voterJwcode + ":" + LocalDateTime.now().toLocalDate(); |
|
|
|
String currentVoteCountStr = stringRedisTemplate.opsForValue().get(redisKey); |
|
|
|
int voteCountToday = currentVoteCountStr == null ? 0 : Integer.parseInt(currentVoteCountStr); |
|
|
|
|
|
|
@ -75,19 +77,19 @@ public class VoteServiceImpl implements VoteService { |
|
|
|
throw new MyException("今日投票次数已达上限"); |
|
|
|
} |
|
|
|
|
|
|
|
String voteStatusKey = "vote_status:" + voterJwcode + ":" + candidateJwcode; |
|
|
|
String voteStatusKey = CACHE_KEY_VOTE_STATUE + voterJwcode + ":" + candidateJwcode; |
|
|
|
Boolean hasVoted = stringRedisTemplate.hasKey(voteStatusKey); |
|
|
|
if (hasVoted != null && hasVoted) { |
|
|
|
throw new MyException("您已经为该候选人投票,不能重复投票"); |
|
|
|
} |
|
|
|
|
|
|
|
String candidateKey = "candidate:" + candidateJwcode; |
|
|
|
String candidateKey = CACHE_KEY_CANDIDATE + candidateJwcode; |
|
|
|
|
|
|
|
// 使用 Redis 的 Hash 增加候选人投票数 |
|
|
|
redisTemplate.opsForHash().increment(candidateKey, "votes", 1); |
|
|
|
|
|
|
|
// 使用 Redis 的 ZSet 增加候选人投票数 |
|
|
|
redisTemplate.opsForZSet().incrementScore("candidate:votes", candidateJwcode, 1); |
|
|
|
redisTemplate.opsForZSet().incrementScore(CACHE_KEY_CANDIDATE + "votes", candidateJwcode, 1); |
|
|
|
|
|
|
|
// 更新 Redis 中的投票次数 |
|
|
|
redisTemplate.opsForValue().increment(redisKey, 1); |
|
|
@ -146,7 +148,7 @@ public class VoteServiceImpl implements VoteService { |
|
|
|
} |
|
|
|
|
|
|
|
private void markVotedStatus(String voterJwcode, List<Candidate> candidateList) { |
|
|
|
String voteStatusKeyPrefix = "vote_status:" + voterJwcode + ":"; |
|
|
|
String voteStatusKeyPrefix = CACHE_KEY_VOTE_STATUE + voterJwcode + ":"; |
|
|
|
Set<String> votedKeys = stringRedisTemplate.keys(voteStatusKeyPrefix + "*"); |
|
|
|
|
|
|
|
if (votedKeys != null) { |
|
|
@ -188,7 +190,7 @@ public class VoteServiceImpl implements VoteService { |
|
|
|
public boolean resetVote() throws MyException { |
|
|
|
if (voterMapper.resetVote() && candidatesMapper.resetVotes()) { |
|
|
|
//删除redis所有缓存 |
|
|
|
redisTemplate.delete(redisTemplate.keys("*")); |
|
|
|
redisTemplate.delete(redisTemplate.keys(KEY_PREFIX + "*")); |
|
|
|
candidateCacheRepository.deleteAllCandidatesFromCache(); |
|
|
|
} else { |
|
|
|
throw new MyException("重置投票失败"); |
|
|
|