-
Redis 缓存设计及实现 -
数据库设计 -
数据库操作 -
开启定时任务持久化存储到数据库
一、Redis 缓存设计及实现
1.1 Redis 安装及运行
Redis 安装请自行查阅相关教程。
1.2 Redis 与 SpringBoot 项目的整合
groupId>org.springframework.bootgroupId>
artifactId>spring-boot-starter-data-redisartifactId>
dependency>
@EnableDiscoveryClient
@EnableSwagger2
@EnableFeignClients(basePackages = “com.solo.coderiver.project.client”)
@EnableCaching
public class UserApplication {public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
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
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException
Jackson2JsonRedisSerializer
1.3 Redis 的数据结构类型
1.4 点赞数据在 Redis 中的存储格式
1.5 操作 Redis
import com.solo.coderiver.user.dto.LikedCountDTO;
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
/**
* 获取Redis中存储的所有点赞数量
* @return
*/
List
}
import com.solo.coderiver.user.dto.LikedCountDTO;
import com.solo.coderiver.user.enums.LikedStatusEnum;
import com.solo.coderiver.user.service.LikedService;
import com.solo.coderiver.user.service.RedisService;
import com.solo.coderiver.user.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;
@Autowired
LikedService likedService;
@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
Cursor
List
while (cursor.hasNext()){
Map.Entry
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();
}
}
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;
}
}
二、数据库设计
`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 ‘用户点赞表’;
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;
}
}
三、数据库操作
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
/**
* 根据被点赞人的id查询点赞列表(即查询都谁给这个人点赞过)
* @param likedUserId 被点赞人的id
* @param pageable
* @return
*/
Page
/**
* 根据点赞人的id查询点赞列表(即查询这个人都给谁点赞过)
* @param likedPostId
* @param pageable
* @return
*/
Page
/**
* 通过被点赞人和点赞人id查询是否存在点赞记录
* @param likedUserId
* @param likedPostId
* @return
*/
UserLike getByLikedUserIdAndLikedPostId(String likedUserId, String likedPostId);
/**
* 将Redis里的点赞数据存入数据库中
*/
void transLikedFromRedis2DB();
/**
* 将Redis中的点赞数量数据存入数据库
*/
void transLikedCountFromRedis2DB();
}
import com.solo.coderiver.user.dataobject.UserLike;
import com.solo.coderiver.user.dto.LikedCountDTO;
import com.solo.coderiver.user.enums.LikedStatusEnum;
import com.solo.coderiver.user.repository.UserLikeRepository;
import com.solo.coderiver.user.service.LikedService;
import com.solo.coderiver.user.service.RedisService;
import com.solo.coderiver.user.service.UserService;
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
return likeRepository.saveAll(list);
}
@Override
public Page
return likeRepository.findByLikedUserIdAndStatus(likedUserId, LikedStatusEnum.LIKE.getCode(), pageable);
}
@Override
public Page
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
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
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);
}
}
}
}
四、开启定时任务持久化存储到数据库
groupId>org.springframework.bootgroupId>
artifactId>spring-boot-starter-quartzartifactId>
dependency>
import com.solo.coderiver.user.task.LikeTask;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@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) //两个小时执行一次
.repeatForever();
return TriggerBuilder.newTrigger().forJob(quartzDetail())
.withIdentity(LIKE_TASK_IDENTITY)
.withSchedule(scheduleBuilder)
.build();
}
}
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
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();
}
}
0 条评论