用springboot将redis点赞数量同步到MySQL写出代码
时间: 2023-05-23 20:05:22 浏览: 177
A:
1. 首先需要添加Redis和MySQL的依赖
```xml
<!-- Redis依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- MySQL依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
```
2. 在application.properties(或application.yml)中配置Redis和MySQL的连接信息
```properties
# Redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=your-redis-password
# MySQL配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/your-database-name?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=your-mysql-username
spring.datasource.password=your-mysql-password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA配置
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
```
3. 创建RedisService类,用于操作Redis
```java
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// 增加点赞数量
public void incrLikes(String key) {
redisTemplate.opsForValue().increment(key);
}
// 减少点赞数量
public void decrLikes(String key) {
redisTemplate.opsForValue().decrement(key);
}
// 获取点赞数量
public Integer getLikes(String key) {
Object value = redisTemplate.opsForValue().get(key);
if (value != null) {
return Integer.valueOf(value.toString());
}
return null;
}
}
```
4. 创建MySQL实体类LikeCount,用于将Redis中的点赞数量同步到MySQL
```java
@Entity
@Table(name = "like_count")
public class LikeCount {
@Id
private Long id;
@Column(name = "`key`")
private String key;
@Column(name = "value")
private Integer value;
// getter和setter方法
}
```
5. 创建LikeCountRepository接口,用于操作MySQL
```java
@Repository
public interface LikeCountRepository extends JpaRepository<LikeCount, Long> {
LikeCount findByKey(String key);
}
```
6. 在对应的Controller中,调用RedisService操作Redis,并将结果存储到MySQL
```java
@RestController
@RequestMapping("/like")
public class LikeController {
@Autowired
private RedisService redisService;
@Autowired
private LikeCountRepository likeCountRepository;
@PostMapping("/{id}")
public void like(@PathVariable Long id) {
String key = "like:" + id;
redisService.incrLikes(key);
Integer likes = redisService.getLikes(key);
if (likes != null) {
LikeCount likeCount = likeCountRepository.findByKey(key);
if (likeCount == null) {
likeCount = new LikeCount();
likeCount.setId(id);
likeCount.setKey(key);
}
likeCount.setValue(likes);
likeCountRepository.save(likeCount);
}
}
}
```
以上就是将Redis中的点赞数量同步到MySQL的具体实现代码。
阅读全文