最近在做一个用户登录日志,把日志信息先存储到redis中,再使用定时任务,存储到数据库中。在网上找了一些资料,发现和这篇文章原理相似,就复现一下这篇文章,并理清思路,记录下来。
1.redis的数据结构
Redis 可以存储键与5种不同数据结构类型之间的映射,这5种数据结构类型分别为String(字符串)、List(列表)、Set(集合)、Hash(散列)和 Zset(有序集合)。
下面来对这5种数据结构类型作简单的介绍:
1.1点赞数据在 Redis 中的存储格式
用Redis 存储两种数据,一种是记录点赞人、被点赞人、点赞状态的数据,另一种是每个用户被点赞了多少次,做个简单的计数。
由于需要记录点赞人和被点赞人,还有点赞状态(点赞、取消点赞),还要固定时间间隔取出 Redis 中所有点赞数据,分析了下 Redis 数据格式中 Hash 最合适。
因为 Hash 里的数据都是存在一个键里,可以通过这个键很方便的把所有的点赞数据都取出。这个键里面的数据还可以存成键值对的形式,方便存入点赞人、被点赞人和点赞状态。
设点赞人的 id 为 likedPostId,被点赞人的 id 为 likedUserId ,点赞时状态为 1,取消点赞状态为 0。将点赞人 id 和被点赞人 id 作为键,两个 id 中间用 :: 隔开,点赞状态作为值。
所以如果用户点赞,存储的键为:likedUserId::likedPostId,对应的值为 1 。
取消点赞,存储的键为:likedUserId::likedPostId,对应的值为 0 。
取数据时把键用 :: 切开就得到了两个id,也很方便。
1.2MySQL数据库设计
数据库表中至少要包含三个字段:被点赞用户id,点赞用户id,点赞状态。再加上主键id,创建时间,修改时间就行了。
建表语句
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`like_num` int(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
create table `user_like`(
`id` int not null auto_increment,
`liked_user_id` varchar(32) not null comment '被点赞的用户id',
`liked_post_id` varchar(32) not null comment '点赞的用户id',
`status` tinyint(1) default '1' comment '点赞状态,0取消,1点赞',
`create_time` timestamp not null default current_timestamp comment '创建时间',
`update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改时间',
primary key(`id`),
INDEX `liked_user_id`(`liked_user_id`),
INDEX `liked_post_id`(`liked_post_id`)
) comment '用户点赞表';
2.上代码
2.1pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lmc</groupId>
<artifactId>springboot-redistodb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-redistodb</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.2config包
RedisConfig.java为redis的一些配置。
package com.lmc.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(jackson2JsonRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
QuartzConfig.java为定时任务Quartz的相关配置。这里不做过多介绍,详情请看这篇文章。
package com.lmc.config;
import com.lmc.task.LikeTask;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
@Configuration
public class QuartzConfig {
private static final String LIKE_TASK_IDENTITY = "LikeTaskQuartz";
@Bean
public JobDetail quartzDetail() {
return JobBuilder.newJob(LikeTask.class).withIdentity(LIKE_TASK_IDENTITY).storeDurably().build();
}
@Bean
public Trigger quartzTrigger() {
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10) //设置时间周期单位秒
//.withIntervalInHours(2) //两个小时执行一次
// .withIntervalInMinutes(1)
.repeatForever();
return TriggerBuilder.newTrigger().forJob(quartzDetail())
.withIdentity(LIKE_TASK_IDENTITY)
.withSchedule(scheduleBuilder)
.build();
}
}
2.3controller包
SetLikeController.java为准备测试数据。
package com.lmc.controller;
import com.lmc.pojo.UserInfo;
import com.lmc.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
/**
* @description:
* @Author: lmc
* @date: 2021/12/25 14:27
*/
@RestController
public class SetLikeController {
@Autowired
RedisService redisService;
@RequestMapping("/like")
public void putLike(){
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
String uuid2 = UUID.randomUUID().toString().trim().replaceAll("-", "");
UserInfo userInfo = new UserInfo(uuid,2);
UserInfo userInfo2 = new UserInfo(uuid2,4);
redisService.saveLiked2Redis(userInfo.getId(),userInfo2.getId());
}
}
2.4dao包
UserInfoRepository.java、UserLikeRepository.java为操作数据库。
package com.lmc.dao;
import com.lmc.pojo.UserInfo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserInfoRepository extends JpaRepository<UserInfo, String> {
UserInfo findUserInfoById(String id);
}
package com.lmc.dao;
import com.lmc.pojo.UserLike;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* @description:
* @Author: lmc
* @date: 2021/12/25 13:26
*/
@Repository
public interface UserLikeRepository extends JpaRepository<UserLike,Integer> {
Page<UserLike> findByLikedUserIdAndStatus(String likedUserId, Integer code, Pageable pageable);
Page<UserLike> findByLikedPostIdAndStatus(String likedPostId, Integer code, Pageable pageable);
UserLike findByLikedUserIdAndLikedPostId(String likedUserId, String likedPostId);
}
2.5pojo包
package com.lmc.pojo;
import lombok.Data;
import java.io.Serializable;
/**
* @description:
* @Author: lmc
* @date: 2021/12/25 13:32
*/
@Data
public class LikedCountDTO implements Serializable {
private static final long serialVersionUID = -2856160546081194945L;
private String id;
private Integer count;
public LikedCountDTO() {
}
public LikedCountDTO(String id, Integer count) {
this.id = id;
this.count = count;
}
}
package com.lmc.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* @description:
* @Author: lmc
* @date: 2021/12/25 13:36
*/
@Data
@Entity
@DynamicUpdate
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo {
@Id
private String id;
//点赞数量
private Integer likeNum;
}
package com.lmc.pojo;
import com.lmc.utils.LikedStatusEnum;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* 用户点赞表
*/
@Entity
@Data
public class UserLike {
//主键id
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
//被点赞的用户的id
private String likedUserId;
//点赞的用户的id
private String likedPostId;
//点赞的状态.默认未点赞
private Integer status = LikedStatusEnum.UNLIKE.getCode();
public UserLike() {
}
public UserLike(String likedUserId, String likedPostId, Integer status) {
this.likedUserId = likedUserId;
this.likedPostId = likedPostId;
this.status = status;
}
}
2.6service包
package com.lmc.service;
import com.lmc.pojo.UserLike;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
public interface LikedService {
/**
* 保存点赞记录
*
* @param userLike
* @return
*/
UserLike save(UserLike userLike);
/**
* 批量保存或修改
*
* @param list
*/
List<UserLike> saveAll(List<UserLike> list);
/**
* 根据被点赞人的id查询点赞列表(即查询都谁给这个人点赞过)
*
* @param likedUserId 被点赞人的id
* @param pageable
* @return
*/
Page<UserLike> getLikedListByLikedUserId(String likedUserId, Pageable pageable);
/**
* 根据点赞人的id查询点赞列表(即查询这个人都给谁点赞过)
*
* @param likedPostId
* @param pageable
* @return
*/
Page<UserLike> getLikedListByLikedPostId(String likedPostId, Pageable pageable);
/**
* 通过被点赞人和点赞人id查询是否存在点赞记录
*
* @param likedUserId
* @param likedPostId
* @return
*/
UserLike getByLikedUserIdAndLikedPostId(String likedUserId, String likedPostId);
/**
* 将Redis里的点赞数据存入数据库中
*/
void transLikedFromRedis2DB();
/**
* 将Redis中的点赞数量数据存入数据库
*/
void transLikedCountFromRedis2DB();
}
package com.lmc.service;
import com.lmc.dao.UserLikeRepository;
import com.lmc.pojo.LikedCountDTO;
import com.lmc.pojo.UserInfo;
import com.lmc.pojo.UserLike;
import com.lmc.utils.LikedStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Slf4j
public class LikedServiceImpl implements LikedService {
@Autowired
UserLikeRepository likeRepository;
@Autowired
RedisService redisService;
@Autowired
UserService userService;
@Override
@Transactional
public UserLike save(UserLike userLike) {
return likeRepository.save(userLike);
}
@Override
@Transactional
public List<UserLike> saveAll(List<UserLike> list) {
return likeRepository.saveAll(list);
}
@Override
public Page<UserLike> getLikedListByLikedUserId(String likedUserId, Pageable pageable) {
return likeRepository.findByLikedUserIdAndStatus(likedUserId, LikedStatusEnum.LIKE.getCode(), pageable);
}
@Override
public Page<UserLike> getLikedListByLikedPostId(String likedPostId, Pageable pageable) {
return likeRepository.findByLikedPostIdAndStatus(likedPostId, LikedStatusEnum.LIKE.getCode(), pageable);
}
@Override
public UserLike getByLikedUserIdAndLikedPostId(String likedUserId, String likedPostId) {
return likeRepository.findByLikedUserIdAndLikedPostId(likedUserId, likedPostId);
}
@Override
@Transactional
public void transLikedFromRedis2DB() {
List<UserLike> list = redisService.getLikedDataFromRedis();
for (UserLike like : list) {
UserLike ul = getByLikedUserIdAndLikedPostId(like.getLikedUserId(), like.getLikedPostId());
if (ul == null) {
//没有记录,直接存入
save(like);
} else {
//有记录,需要更新
ul.setStatus(like.getStatus());
save(ul);
}
}
}
@Override
@Transactional
public void transLikedCountFromRedis2DB() {
List<LikedCountDTO> list = redisService.getLikedCountFromRedis();
for (LikedCountDTO dto : list) {
UserInfo user = userService.findById(dto.getId());
//点赞数量属于无关紧要的操作,出错无需抛异常
if (user != null) {
Integer likeNum = user.getLikeNum() + dto.getCount();
user.setLikeNum(likeNum);
//更新点赞数量
userService.updateInfo(user);
}
}
}
}
package com.lmc.service;
import com.lmc.pojo.LikedCountDTO;
import com.lmc.pojo.UserLike;
import java.util.List;
public interface RedisService {
/**
* 点赞。状态为1
*
* @param likedUserId
* @param likedPostId
*/
void saveLiked2Redis(String likedUserId, String likedPostId);
/**
* 取消点赞。将状态改变为0
*
* @param likedUserId
* @param likedPostId
*/
void unlikeFromRedis(String likedUserId, String likedPostId);
/**
* 从Redis中删除一条点赞数据
*
* @param likedUserId
* @param likedPostId
*/
void deleteLikedFromRedis(String likedUserId, String likedPostId);
/**
* 该用户的点赞数加1
*
* @param likedUserId
*/
void incrementLikedCount(String likedUserId);
/**
* 该用户的点赞数减1
*
* @param likedUserId
*/
void decrementLikedCount(String likedUserId);
/**
* 获取Redis中存储的所有点赞数据
*
* @return
*/
List<UserLike> getLikedDataFromRedis();
/**
* 获取Redis中存储的所有点赞数量
*
* @return
*/
List<LikedCountDTO> getLikedCountFromRedis();
}
package com.lmc.service;
import com.lmc.pojo.LikedCountDTO;
import com.lmc.pojo.UserLike;
import com.lmc.utils.LikedStatusEnum;
import com.lmc.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
public class RedisServiceImpl implements RedisService {
@Autowired
RedisTemplate redisTemplate;
@Override
public void saveLiked2Redis(String likedUserId, String likedPostId) {
String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId);
redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED, key, LikedStatusEnum.LIKE.getCode());
}
@Override
public void unlikeFromRedis(String likedUserId, String likedPostId) {
String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId);
redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_USER_LIKED, key, LikedStatusEnum.UNLIKE.getCode());
}
@Override
public void deleteLikedFromRedis(String likedUserId, String likedPostId) {
String key = RedisKeyUtils.getLikedKey(likedUserId, likedPostId);
redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED, key);
}
@Override
public void incrementLikedCount(String likedUserId) {
redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, likedUserId, 1);
}
@Override
public void decrementLikedCount(String likedUserId) {
redisTemplate.opsForHash().increment(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, likedUserId, -1);
}
@Override
public List<UserLike> getLikedDataFromRedis() {
Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_USER_LIKED, ScanOptions.NONE);
List<UserLike> list = new ArrayList<>();
while (cursor.hasNext()) {
Map.Entry<Object, Object> entry = cursor.next();
String key = (String) entry.getKey();
//分离出 likedUserId,likedPostId
String[] split = key.split("::");
String likedUserId = split[0];
String likedPostId = split[1];
Integer value = (Integer) entry.getValue();
//组装成 UserLike 对象
UserLike userLike = new UserLike(likedUserId, likedPostId, value);
list.add(userLike);
//存到 list 后从 Redis 中删除
redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED, key);
}
return list;
}
@Override
public List<LikedCountDTO> getLikedCountFromRedis() {
Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, ScanOptions.NONE);
List<LikedCountDTO> list = new ArrayList<>();
while (cursor.hasNext()) {
Map.Entry<Object, Object> map = cursor.next();
//将点赞数量存储在 LikedCountDT
String key = (String) map.getKey();
LikedCountDTO dto = new LikedCountDTO(key, (Integer) map.getValue());
list.add(dto);
//从Redis中删除这条记录
redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, key);
}
return list;
}
}
package com.lmc.service;
import com.lmc.dao.UserInfoRepository;
import com.lmc.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
/**
* @description:
* @Author: lmc
* @date: 2021/12/25 13:37
*/
@Service
public interface UserService {
/**
* 通过id查询用户
*
* @param id
* @return
*/
UserInfo findById(String id);
/**
* 更新个人信息
*
* @param userInfo
* @return
*/
UserInfo updateInfo(UserInfo userInfo);
}
package com.lmc.service;
import com.lmc.dao.UserInfoRepository;
import com.lmc.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @description:
* @Author: lmc
* @date: 2021/12/25 14:14
*/
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserInfoRepository userRepository;
@Override
@Transactional
public UserInfo updateInfo(UserInfo userInfo) {
UserInfo result = userRepository.save(userInfo);
return result;
}
@Override
public UserInfo findById(String id) {
return userRepository.findUserInfoById(id);
}
}
2.7task
package com.lmc.task;
import com.lmc.service.LikedService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 点赞的定时任务
*/
@Slf4j
public class LikeTask extends QuartzJobBean {
@Autowired
LikedService likedService;
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
log.info("LikeTask-------- {}", sdf.format(new Date()));
//将 Redis 里的点赞信息同步到数据库里
likedService.transLikedFromRedis2DB();
likedService.transLikedCountFromRedis2DB();
}
}
2.8utils包
package com.lmc.utils;
import lombok.Getter;
/**
* 用户点赞的状态
*/
@Getter
public enum LikedStatusEnum {
LIKE(1, "点赞"),
UNLIKE(0, "取消点赞/未点赞")
;
private Integer code;
private String msg;
LikedStatusEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
package com.lmc.utils;
public class RedisKeyUtils {
//保存用户点赞数据的key
public static final String MAP_KEY_USER_LIKED = "MAP_USER_LIKED";
//保存用户被点赞数量的key
public static final String MAP_KEY_USER_LIKED_COUNT = "MAP_USER_LIKED_COUNT";
/**
* 拼接被点赞的用户id和点赞的人的id作为key。格式 222222::333333
*
* @param likedUserId 被点赞的人id
* @param likedPostId 点赞的人的id
* @return
*/
public static String getLikedKey(String likedUserId, String likedPostId) {
StringBuilder builder = new StringBuilder();
builder.append(likedUserId);
builder.append("::");
builder.append(likedPostId);
return builder.toString();
}
}
package com.lmc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories
public class SpringbootRedistodbApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootRedistodbApplication.class, args);
}
}
application.properties
spring.datasource.username=root
spring.datasource.password=xxxxxx
spring.datasource.url=jdbc:mysql://localhost:3306/xxxx?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 配置redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=xxxxxx
2.9代码结构
3.测试
启动项目,请求调用/like接口,准备测试数据,每10秒钟就会自动把redis中的数据转存到数据库中。
原文链接:点赞模块设计 - Redis缓存 + 定时写入数据库实现高性能点赞功能 - 掘金