Browse Source

提交

test
lenghui 5 months ago
parent
commit
d4eb8f644e
  1. 7
      pom.xml
  2. 15
      src/main/java/com/lh/bean/VoteMessage.java
  3. 7
      src/main/java/com/lh/controller/VoteController.java
  4. 3
      src/main/java/com/lh/mapper/CandidatesMapper.java
  5. 3
      src/main/java/com/lh/mapper/VoterMapper.java
  6. 74
      src/main/java/com/lh/service/VoteConsumer.java
  7. 26
      src/main/java/com/lh/service/VoteProducer.java
  8. 2
      src/main/java/com/lh/service/VoteService.java
  9. 53
      src/main/java/com/lh/service/VoteServiceImpl.java
  10. 3
      src/main/resources/com/lh/mapper/CandidatesMapper.xml
  11. 3
      src/main/resources/com/lh/mapper/VoterMapper.xml

7
pom.xml

@ -3,7 +3,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lh</groupId>
<artifactId>vote_invest</artifactId>
<artifactId>vote_invest_simple</artifactId>
<version>0.0.2</version>
<name>vote_invest</name>
<description>Demo project for Spring Boot</description>
@ -54,11 +54,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- kafka -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<!-- Apache HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>

15
src/main/java/com/lh/bean/VoteMessage.java

@ -1,15 +0,0 @@
package com.lh.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class VoteMessage {
private String voterJwcode; // 投票人IDJWCode
private String candidateJwcode; // 候选人IDJWCode
private String voterName; // 投票人姓名
private String voteTime; // 投票时间
}

7
src/main/java/com/lh/controller/VoteController.java

@ -46,4 +46,11 @@ public class VoteController {
public RespBean getVotesByCandidate(@PathVariable("candidateJwcode") String candidateJwcode) throws MyException {
return RespBean.ok("获取成功",voteService.getVotesByCandidate(candidateJwcode));
}
//重置所有投票记录
@GetMapping("/resetVote")
public RespBean resetVote() throws MyException {
boolean result = voteService.resetVote();
return RespBean.ok("重置成功",result);
}
}

3
src/main/java/com/lh/mapper/CandidatesMapper.java

@ -14,4 +14,7 @@ public interface CandidatesMapper {
Candidate getByCandidateJwcode(@Param("jwcode") String jwcode);
//候选人票数+1
boolean addVotes(@Param("jwcode") String jwcode);
//重置
boolean resetVotes();
}

3
src/main/java/com/lh/mapper/VoterMapper.java

@ -14,4 +14,7 @@ public interface VoterMapper {
void insertVote(@Param("jwcode") String jwcode, @Param("candidateJwcode") String candidateJwcode,@Param("name") String namne);
//根据候选人的jwcode查询投票记录
List<Voter> getVotesByCandidate(@Param("candidateJwcode") String candidateJwcode);
//重置
boolean resetVote();
}

74
src/main/java/com/lh/service/VoteConsumer.java

@ -1,74 +0,0 @@
package com.lh.service;
import com.lh.bean.Candidate;
import com.lh.exception.MyException;
import com.lh.mapper.CandidatesMapper;
import com.lh.mapper.VoterMapper;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
@EnableKafka
public class VoteConsumer {
@Autowired
private VoterMapper voterMapper;
@Autowired
private CandidatesMapper candidatesMapper;
@Autowired
private StringRedisTemplate redisTemplate;
@KafkaListener(topics = "vote-topic", groupId = "vote-group")
public void handleVoteMessage(ConsumerRecord<String, String> record) throws MyException {
String message = record.value();
// 将消息分割为投票信息
String[] parts = message.split(",");
String voterJwcode = parts[0];
String candidateJwcode = parts[1];
String voterName = parts[2];
String voteTime = parts[3];
// 处理投票
processVote(voterJwcode, candidateJwcode, voterName, voteTime);
}
private boolean processVote(String voterJwcode, String candidateJwcode, String voterName, String voteTime) throws MyException {
// 获取候选人信息
Candidate candidate = candidatesMapper.getByCandidateJwcode(candidateJwcode);
// 2. 获取候选人信息
if (candidate == null) {
throw new MyException("候选人不存在!");
}
// 3. 检查用户是否已经为该候选人投过票
//List<Voter> hasVotes = voterMapper.countVotesToday(voterJwcode);
////遍历列表判断是否有记录
//boolean flag = true;
//for (Voter vote : hasVotes) {
// if (vote.getCandidateJwCode().equals(candidateJwcode)) {
// flag = false;
// }
//}
//if (!flag){
// throw new MyException("已投票,可以选择其他人试试哦~");
//}
// 4. 增加候选人票数
if (!candidatesMapper.addVotes(candidateJwcode)) {
throw new MyException ("候选人票数更新失败,请联系管理员!");
}
// 5. 插入投票记录
voterMapper.insertVote(voterJwcode, candidateJwcode, voterName);
System.out.println("投票成功!用户:" + voterJwcode + " 投给了 " + candidateJwcode);
return true;
}
}

26
src/main/java/com/lh/service/VoteProducer.java

@ -1,26 +0,0 @@
package com.lh.service;
import com.lh.bean.VoteMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class VoteProducer {
private static final String TOPIC = "vote-topic"; // Kafka topic
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
// 发送投票消息
public void sendVoteMessage(VoteMessage voteMessage) {
String message = String.format("%s,%s,%s,%s",
voteMessage.getVoterJwcode(),
voteMessage.getCandidateJwcode(),
voteMessage.getVoterName(),
voteMessage.getVoteTime());
kafkaTemplate.send(TOPIC, message); // 将投票信息发送到Kafka
}
}

2
src/main/java/com/lh/service/VoteService.java

@ -13,4 +13,6 @@ public interface VoteService {
List<Candidate> getCandidates(String VoterJwcode);
//获取某个候选人的被投票记录
List<Voter> getVotesByCandidate(String candidateJwcode) throws MyException;
//重置投票
boolean resetVote() throws MyException;
}

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

@ -1,23 +1,22 @@
package com.lh.service;
import com.lh.bean.Candidate;
import com.lh.bean.VoteMessage;
import com.lh.bean.Voter;
import com.lh.config.CandidateCacheRepository;
import com.lh.exception.MyException;
import com.lh.mapper.CandidatesMapper;
import com.lh.mapper.VoterMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
@ -39,8 +38,6 @@ public class VoteServiceImpl implements VoteService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private VoteProducer voteProducer;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private CandidateCacheRepository candidateCacheRepository;
@ -104,8 +101,8 @@ public class VoteServiceImpl implements VoteService {
// 更新投票重复键
stringRedisTemplate.opsForValue().set(voteStatusKey, "true", secondsUntilEndOfDay, TimeUnit.SECONDS);
// 将投票请求发送到 Kafka 消息队列
voteProducer.sendVoteMessage(new VoteMessage(voterJwcode, candidateJwcode, voterName, Timestamp.valueOf(LocalDateTime.now()).toString()));
// 数据库操作
processVote(voterJwcode, candidateJwcode, voterName);
return dailyVoteLimit - voteCountToday - 1;
}
@ -161,4 +158,44 @@ public class VoteServiceImpl implements VoteService {
}
}
}
@Async
@Transactional(rollbackFor = Exception.class)
protected void processVote(String voterJwcode, String candidateJwcode, String voterName) throws MyException {
// 获取候选人信息
Candidate candidate = candidatesMapper.getByCandidateJwcode(candidateJwcode);
// 2. 获取候选人信息
if (candidate == null) {
throw new MyException("候选人不存在!");
}
// 4. 增加候选人票数
if (!candidatesMapper.addVotes(candidateJwcode)) {
throw new MyException ("候选人票数更新失败,请联系管理员!");
}
// 5. 插入投票记录
voterMapper.insertVote(voterJwcode, candidateJwcode, voterName);
System.out.println("投票成功!用户:" + voterJwcode + " 投给了 " + candidateJwcode);
}
//重置投票
@Override
@Transactional(rollbackFor = Exception.class)
public boolean resetVote() throws MyException {
if (voterMapper.resetVote() && candidatesMapper.resetVotes()){
//删除redis所有缓存
redisTemplate.delete(redisTemplate.keys("*"));
candidateCacheRepository.deleteAllCandidatesFromCache();
} else {
throw new MyException("重置投票失败");
}
//重新初始化
initCandidatesCache();
return true;
}
}

3
src/main/resources/com/lh/mapper/CandidatesMapper.xml

@ -4,6 +4,9 @@
<insert id="addVotes">
update candidates set votes = votes + 1 where jwcode = #{jwcode}
</insert>
<update id="resetVotes">
update candidates set votes = 0
</update>
<select id="getCandidates" resultType="com.lh.bean.Candidate">
select * from candidates order by votes desc
</select>

3
src/main/resources/com/lh/mapper/VoterMapper.xml

@ -5,6 +5,9 @@
INSERT INTO voters(jwcode, candidate_jwcode, name)
VALUES(#{jwcode}, #{candidateJwcode}, #{name})
</insert>
<delete id="resetVote">
DELETE FROM voters
</delete>
<select id="countVotesToday" resultType="com.lh.bean.Voter">
SELECT * FROM voters WHERE jwcode = #{jwcode} AND DATE(vote_time) = CURDATE()
</select>

Loading…
Cancel
Save