Browse Source

维护redis前缀,修复删除redis所有数据问题

master
王琳 5 months ago
parent
commit
9256ca002e
  1. 9
      src/main/java/com/lh/bean/RedisKey.java
  2. 16
      src/main/java/com/lh/config/CandidateCacheRepository.java
  3. 20
      src/main/java/com/lh/service/VoteServiceImpl.java

9
src/main/java/com/lh/bean/RedisKey.java

@ -0,0 +1,9 @@
package com.lh.bean;
public interface RedisKey {
String KEY_PREFIX = "homilychart-vote-";
String CACHE_KEY_VOTE_COUNT = KEY_PREFIX + "vote_count:";
String CACHE_KEY_VOTE_STATUE = KEY_PREFIX + "vote_status:";
String CACHE_KEY_CANDIDATE = KEY_PREFIX + "candidate:";
}

16
src/main/java/com/lh/config/CandidateCacheRepository.java

@ -10,6 +10,8 @@ import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.Set; import java.util.Set;
import static com.lh.bean.RedisKey.CACHE_KEY_CANDIDATE;
@Repository @Repository
public class CandidateCacheRepository { public class CandidateCacheRepository {
@ -27,7 +29,7 @@ public class CandidateCacheRepository {
// 保存候选人信息到 Redis // 保存候选人信息到 Redis
public void saveCandidate(Candidate candidate) { public void saveCandidate(Candidate candidate) {
String key = "candidate:" + candidate.getJwCode();
String key = CACHE_KEY_CANDIDATE + candidate.getJwCode();
// 确保所有值都是字符串类型 // 确保所有值都是字符串类型
redisTemplate.opsForHash().put(key, "id", String.valueOf(candidate.getId())); redisTemplate.opsForHash().put(key, "id", String.valueOf(candidate.getId()));
@ -37,12 +39,12 @@ public class CandidateCacheRepository {
redisTemplate.opsForHash().put(key, "votes", String.valueOf(candidate.getVotes())); redisTemplate.opsForHash().put(key, "votes", String.valueOf(candidate.getVotes()));
// 更新 ZSET // 更新 ZSET
redisTemplate.opsForZSet().add("candidate:votes", candidate.getJwCode(), candidate.getVotes());
redisTemplate.opsForZSet().add(CACHE_KEY_CANDIDATE + "votes", candidate.getJwCode(), candidate.getVotes());
} }
// 获取候选人详细信息 // 获取候选人详细信息
public Candidate getCandidate(String jwCode) { public Candidate getCandidate(String jwCode) {
String key = "candidate:" + jwCode;
String key = CACHE_KEY_CANDIDATE + jwCode;
Candidate candidate = new Candidate(); Candidate candidate = new Candidate();
Object idObj = redisTemplate.opsForHash().get(key, "id"); Object idObj = redisTemplate.opsForHash().get(key, "id");
@ -68,17 +70,17 @@ public class CandidateCacheRepository {
// 获取所有候选人的 jwCode 按投票数排序 // 获取所有候选人的 jwCode 按投票数排序
public Set<Object> getCandidateJwCodesByVotes() { public Set<Object> getCandidateJwCodesByVotes() {
return redisTemplate.opsForZSet().reverseRange("candidate:votes", 0, -1);
return redisTemplate.opsForZSet().reverseRange(CACHE_KEY_CANDIDATE + "votes", 0, -1);
} }
// 删除 Redis 中所有候选人数据 // 删除 Redis 中所有候选人数据
public void deleteAllCandidatesFromCache() { public void deleteAllCandidatesFromCache() {
Set<Object> jwCodes = redisTemplate.opsForZSet().range("candidate:votes", 0, -1);
Set<Object> jwCodes = redisTemplate.opsForZSet().range(CACHE_KEY_CANDIDATE + "votes", 0, -1);
if (jwCodes != null) { if (jwCodes != null) {
for (Object jwCode : jwCodes) { for (Object jwCode : jwCodes) {
redisTemplate.delete("candidate:" + jwCode);
redisTemplate.delete(CACHE_KEY_CANDIDATE + jwCode);
} }
} }
redisTemplate.delete("candidate:votes");
redisTemplate.delete(CACHE_KEY_CANDIDATE + "votes");
} }
} }

20
src/main/java/com/lh/service/VoteServiceImpl.java

@ -24,6 +24,8 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static com.lh.bean.RedisKey.*;
@Service @Service
public class VoteServiceImpl implements VoteService { public class VoteServiceImpl implements VoteService {
@ -67,7 +69,7 @@ public class VoteServiceImpl implements VoteService {
throw new MyException("候选人不存在"); 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); String currentVoteCountStr = stringRedisTemplate.opsForValue().get(redisKey);
int voteCountToday = currentVoteCountStr == null ? 0 : Integer.parseInt(currentVoteCountStr); int voteCountToday = currentVoteCountStr == null ? 0 : Integer.parseInt(currentVoteCountStr);
@ -75,19 +77,19 @@ public class VoteServiceImpl implements VoteService {
throw new MyException("今日投票次数已达上限"); throw new MyException("今日投票次数已达上限");
} }
String voteStatusKey = "vote_status:" + voterJwcode + ":" + candidateJwcode;
String voteStatusKey = CACHE_KEY_VOTE_STATUE + voterJwcode + ":" + candidateJwcode;
Boolean hasVoted = stringRedisTemplate.hasKey(voteStatusKey); Boolean hasVoted = stringRedisTemplate.hasKey(voteStatusKey);
if (hasVoted != null && hasVoted) { if (hasVoted != null && hasVoted) {
throw new MyException("您已经为该候选人投票,不能重复投票"); throw new MyException("您已经为该候选人投票,不能重复投票");
} }
String candidateKey = "candidate:" + candidateJwcode;
String candidateKey = CACHE_KEY_CANDIDATE + candidateJwcode;
// 使用 Redis Hash 增加候选人投票数 // 使用 Redis Hash 增加候选人投票数
redisTemplate.opsForHash().increment(candidateKey, "votes", 1); redisTemplate.opsForHash().increment(candidateKey, "votes", 1);
// 使用 Redis ZSet 增加候选人投票数 // 使用 Redis ZSet 增加候选人投票数
redisTemplate.opsForZSet().incrementScore("candidate:votes", candidateJwcode, 1);
redisTemplate.opsForZSet().incrementScore(CACHE_KEY_CANDIDATE + "votes", candidateJwcode, 1);
// 更新 Redis 中的投票次数 // 更新 Redis 中的投票次数
redisTemplate.opsForValue().increment(redisKey, 1); redisTemplate.opsForValue().increment(redisKey, 1);
@ -124,7 +126,7 @@ public class VoteServiceImpl implements VoteService {
candidateList.add(candidate); candidateList.add(candidate);
} }
} }
}catch(Exception e){
} catch (Exception e) {
//如果缓存中获取候选人失败则从数据库中获取候选人列表 //如果缓存中获取候选人失败则从数据库中获取候选人列表
candidateList = candidatesMapper.getCandidates(); candidateList = candidatesMapper.getCandidates();
} }
@ -146,7 +148,7 @@ public class VoteServiceImpl implements VoteService {
} }
private void markVotedStatus(String voterJwcode, List<Candidate> candidateList) { 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 + "*"); Set<String> votedKeys = stringRedisTemplate.keys(voteStatusKeyPrefix + "*");
if (votedKeys != null) { if (votedKeys != null) {
@ -172,7 +174,7 @@ public class VoteServiceImpl implements VoteService {
// 4. 增加候选人票数 // 4. 增加候选人票数
if (!candidatesMapper.addVotes(candidateJwcode)) { if (!candidatesMapper.addVotes(candidateJwcode)) {
throw new MyException ("候选人票数更新失败,请联系管理员!");
throw new MyException("候选人票数更新失败,请联系管理员!");
} }
// 5. 插入投票记录 // 5. 插入投票记录
@ -186,9 +188,9 @@ public class VoteServiceImpl implements VoteService {
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public boolean resetVote() throws MyException { public boolean resetVote() throws MyException {
if (voterMapper.resetVote() && candidatesMapper.resetVotes()){
if (voterMapper.resetVote() && candidatesMapper.resetVotes()) {
//删除redis所有缓存 //删除redis所有缓存
redisTemplate.delete(redisTemplate.keys("*"));
redisTemplate.delete(redisTemplate.keys(KEY_PREFIX + "*"));
candidateCacheRepository.deleteAllCandidatesFromCache(); candidateCacheRepository.deleteAllCandidatesFromCache();
} else { } else {
throw new MyException("重置投票失败"); throw new MyException("重置投票失败");

Loading…
Cancel
Save