You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.6 KiB

5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
  1. package com.lh.service;
  2. import com.lh.bean.Candidate;
  3. import com.lh.exception.MyException;
  4. import com.lh.mapper.CandidatesMapper;
  5. import com.lh.mapper.VoterMapper;
  6. import org.apache.kafka.clients.consumer.ConsumerRecord;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.data.redis.core.StringRedisTemplate;
  9. import org.springframework.kafka.annotation.EnableKafka;
  10. import org.springframework.kafka.annotation.KafkaListener;
  11. import org.springframework.stereotype.Service;
  12. @Service
  13. @EnableKafka
  14. public class VoteConsumer {
  15. @Autowired
  16. private VoterMapper voterMapper;
  17. @Autowired
  18. private CandidatesMapper candidatesMapper;
  19. @Autowired
  20. private StringRedisTemplate redisTemplate;
  21. @KafkaListener(topics = "vote-topic", groupId = "vote-group")
  22. public void handleVoteMessage(ConsumerRecord<String, String> record) throws MyException {
  23. String message = record.value();
  24. // 将消息分割为投票信息
  25. String[] parts = message.split(",");
  26. String voterJwcode = parts[0];
  27. String candidateJwcode = parts[1];
  28. String voterName = parts[2];
  29. String voteTime = parts[3];
  30. // 处理投票
  31. processVote(voterJwcode, candidateJwcode, voterName, voteTime);
  32. }
  33. private boolean processVote(String voterJwcode, String candidateJwcode, String voterName, String voteTime) throws MyException {
  34. // 获取候选人信息
  35. Candidate candidate = candidatesMapper.getByCandidateJwcode(candidateJwcode);
  36. // 2. 获取候选人信息
  37. if (candidate == null) {
  38. throw new MyException("候选人不存在!");
  39. }
  40. // 3. 检查用户是否已经为该候选人投过票
  41. //List<Voter> hasVotes = voterMapper.countVotesToday(voterJwcode);
  42. ////遍历列表,判断是否有记录
  43. //boolean flag = true;
  44. //for (Voter vote : hasVotes) {
  45. // if (vote.getCandidateJwCode().equals(candidateJwcode)) {
  46. // flag = false;
  47. // }
  48. //}
  49. //if (!flag){
  50. // throw new MyException("已投票,可以选择其他人试试哦~");
  51. //}
  52. // 4. 增加候选人票数
  53. if (!candidatesMapper.addVotes(candidateJwcode)) {
  54. throw new MyException ("候选人票数更新失败,请联系管理员!");
  55. }
  56. // 5. 插入投票记录
  57. voterMapper.insertVote(voterJwcode, candidateJwcode, voterName);
  58. System.out.println("投票成功!用户:" + voterJwcode + " 投给了 " + candidateJwcode);
  59. return true;
  60. }
  61. }