Compare commits

...
3 Commits
Author SHA1 Message Date
wonder 2e7a7c060f 🔄Update: 优化点赞缓存逻辑,添加取消点赞标记 2025-10-23 22:46:30 +08:00
wonder 1dc2bcf8bf ✨Feat: 完善点赞业务二级缓存 2025-10-23 18:57:04 +08:00
wonder 61772a067a 🔄Update: 实现二级缓存的访问 2025-10-23 18:49:53 +08:00
4 changed files with 91 additions and 8 deletions
@@ -18,4 +18,6 @@ public class ThumbConstant {
* 用于作为Redis中存储临时点赞信息的key前缀
*/
public static final String TEMP_THUMB_KEY_PREFIX = "temp_thumb:%s";
public static final Long UN_THUMB_CONSTANT = 0L;
}
@@ -2,8 +2,11 @@ package cn.hezhaohui.thumb.manager.cache;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@@ -14,6 +17,9 @@ public class CacheManager {
private TopK hotKeyDetector;
private Cache<String, Object> localCache;
@Resource
private RedisTemplate<String, Object> redisTemplate;
@Bean
public TopK getHotKeyDetector() {
return hotKeyDetector = new HeavyKeeper(
@@ -37,4 +43,51 @@ public class CacheManager {
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
}
// 构造复合 Key
private String buildCacheKey(String hashKey, String key) {
return hashKey + ":" + key;
}
public Object get(String hashKey, String key) {
String compositeKey = this.buildCacheKey(hashKey, key);
// 1. 查本地缓存
Object value = localCache.getIfPresent(compositeKey);
if (value != null) {
log.info("本地缓存获取到数据 {} = {}", compositeKey, value);
// 记录访问次数
hotKeyDetector.add(key, 1);
return value;
}
// 2. 本地缓存未命中,查询 Redis
Object redisValue = redisTemplate.opsForHash().get(hashKey, key);
if (redisValue == null) {
return null;
}
// 3. 记录访问次数
AddResult addResult = hotKeyDetector.add(key, 1);
// 4. 缓存数据 热Key
if (addResult.isHotKey()) {
localCache.put(compositeKey, redisValue);
}
return redisValue;
}
public void putIfPresent(String hashKey, String key, Object value) {
String compositeKey = this.buildCacheKey(hashKey, key);
Object object = localCache.getIfPresent(compositeKey);
if (object == null) {
return;
}
localCache.put(compositeKey, value);
}
// 定时清理过期的 HotKey 数据
@Scheduled(fixedRate = 20, timeUnit = TimeUnit.SECONDS)
public void cleanHotKeys() {
hotKeyDetector.fading();
}
}
@@ -1,7 +1,9 @@
package cn.hezhaohui.thumb.service.impl;
import cn.hezhaohui.thumb.constant.ThumbConstant;
import cn.hezhaohui.thumb.exception.BusinessException;
import cn.hezhaohui.thumb.exception.ErrorCode;
import cn.hezhaohui.thumb.manager.cache.CacheManager;
import cn.hezhaohui.thumb.model.dto.DoThumbRequest;
import cn.hezhaohui.thumb.model.entity.Blog;
import cn.hezhaohui.thumb.model.entity.User;
@@ -14,6 +16,7 @@ import cn.hezhaohui.thumb.service.ThumbService;
import cn.hezhaohui.thumb.mapper.ThumbMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
@@ -23,7 +26,8 @@ import org.springframework.transaction.support.TransactionTemplate;
* @description 针对表【thumb】的数据库操作Service实现
* @createDate 2025-10-18 14:51:00
*/
@Service("thumbServiceDB")
@Service("thumbService")
@Slf4j
public class ThumbServiceImpl extends ServiceImpl<ThumbMapper, Thumb>
implements ThumbService{
@@ -39,6 +43,9 @@ public class ThumbServiceImpl extends ServiceImpl<ThumbMapper, Thumb>
@Resource
private RedisTemplate<String, Object> redisTemplate;
@Resource
private CacheManager cacheManager;
@Override
public Boolean doThumb(DoThumbRequest doThumbRequest, HttpServletRequest request) {
if (doThumbRequest == null || doThumbRequest.getBlogId() == null) {
@@ -68,7 +75,13 @@ public class ThumbServiceImpl extends ServiceImpl<ThumbMapper, Thumb>
boolean success = update && this.save(thumb);
// 点赞记录存入 Redis
if (success) {
redisTemplate.opsForHash().put(RedisKeyUtil.getUserThumbKey(loginUser.getId()), blogId.toString(), thumb.getId());
// 一级缓存
// redisTemplate.opsForHash().put(RedisKeyUtil.getUserThumbKey(loginUser.getId()), blogId.toString(), thumb.getId());
String hashKey = ThumbConstant.USER_THUMB_KEY_PREFIX + loginUser.getId();
String filedKey = blogId.toString();
Long realThumbId = thumb.getId();
redisTemplate.opsForHash().put(hashKey, filedKey, realThumbId);
cacheManager.putIfPresent(hashKey, filedKey, realThumbId);
}
return success;
});
@@ -87,8 +100,8 @@ public class ThumbServiceImpl extends ServiceImpl<ThumbMapper, Thumb>
return transactionTemplate.execute(status -> {
Long blogId = doThumbRequest.getBlogId();
// 判断是否已点过赞
Object thumbIdObj = redisTemplate.opsForHash().get(RedisKeyUtil.getUserThumbKey(loginUser.getId()), blogId.toString());
if (thumbIdObj == null) {
Object thumbIdObj = cacheManager.get(ThumbConstant.USER_THUMB_KEY_PREFIX + loginUser.getId(), blogId.toString());
if (thumbIdObj == null || thumbIdObj.equals(ThumbConstant.UN_THUMB_CONSTANT)) {
throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户未点赞");
}
Long thumbId = ((Number) thumbIdObj).longValue();
@@ -99,9 +112,14 @@ public class ThumbServiceImpl extends ServiceImpl<ThumbMapper, Thumb>
.update();
// 更新点赞表数据
// 两者一起执行
boolean success = update && this.removeById(thumbId);
boolean success = update && this.removeById(((Number)thumbIdObj).longValue());
if (success) {
redisTemplate.opsForHash().delete(RedisKeyUtil.getUserThumbKey(loginUser.getId()), blogId.toString());
// 一级缓存
// redisTemplate.opsForHash().delete(RedisKeyUtil.getUserThumbKey(loginUser.getId()), blogId.toString());
String hashKey = ThumbConstant.USER_THUMB_KEY_PREFIX + loginUser.getId();
String fieldKey = blogId.toString();
redisTemplate.opsForHash().delete(hashKey, fieldKey);
cacheManager.putIfPresent(hashKey, fieldKey, ThumbConstant.UN_THUMB_CONSTANT);
}
return success;
});
@@ -110,7 +128,17 @@ public class ThumbServiceImpl extends ServiceImpl<ThumbMapper, Thumb>
@Override
public Boolean hasThumb(Long blogId, Long userId) {
return redisTemplate.opsForHash().hasKey(RedisKeyUtil.getUserThumbKey(userId), blogId.toString());
// 一级缓存
// return redisTemplate.opsForHash().hasKey(RedisKeyUtil.getUserThumbKey(userId), blogId.toString());
Object thumbIdObj = cacheManager.get(ThumbConstant.USER_THUMB_KEY_PREFIX + userId, blogId.toString());;
if (thumbIdObj == null) {
return false;
}
Long thumbId = ((Number) thumbIdObj).longValue();
return !thumbId.equals(ThumbConstant.UN_THUMB_CONSTANT);
}
}
@@ -29,7 +29,7 @@ import java.util.Arrays;
* @description 针对表【thumb】的数据库操作Service实现
* @createDate 2025-10-18 14:51:00
*/
@Service("thumbService")
@Service("thumbServiceRedis")
public class ThumbServiceRedisImpl extends ServiceImpl<ThumbMapper, Thumb>
implements ThumbService{