使用Spring Boot实现Redis多数据库缓存

Redis多数据库存储实现用户行为缓存

在我的系统中,为了优化用户行为数据的存储与访问效率,我引入了Redis缓存,并将数据分布在不同的Redis数据库中。通过这种方式,可以减少单一数据库的负载,提高系统的整体性能。

主要实现步骤
  1. Redis配置

    • 配置两个Redis连接工厂,分别用于存储Token和用户行为数据。
    • 创建对应的RedisTemplate实例,指定不同的连接工厂及序列化方式。
  2. 用户行为服务

    • 通过UserBehaviorService接口及其实现类UserBehaviorServiceImpl,实现对用户点赞、收藏、评论、浏览行为的记录。
    • 在操作数据库的同时,将用户行为数据存储到Redis中以提高读取效率。
  3. Token拦截器

    • 使用TokenInterceptor类在每次请求前验证Token。
    • 验证通过后,将用户信息存储到ThreadLocal中,供后续操作使用。
代码实现
Redis配置类
java 复制代码
@Configuration
public class RedisConfig {

    @Value("${spring.data.redis.host}")
    private String redisHost;

    @Value("${spring.data.redis.port}")
    private int redisPort;

    @Value("${spring.data.redis.password}")
    private String redisPassword;

    @Bean(name = "tokenRedisConnectionFactory")
    public RedisConnectionFactory tokenRedisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, redisPort);
        config.setPassword(redisPassword);
        config.setDatabase(0);
        return new LettuceConnectionFactory(config);
    }

    @Bean(name = "userBehaviorRedisConnectionFactory")
    public RedisConnectionFactory userBehaviorRedisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, redisPort);
        config.setPassword(redisPassword);
        config.setDatabase(1);
        return new LettuceConnectionFactory(config);
    }

    @Bean(name = "redisTemplate")
    public StringRedisTemplate redisTemplate(@Qualifier("tokenRedisConnectionFactory") RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }

    @Bean(name = "userBehaviorRedisTemplate")
    public RedisTemplate<String, Map<String, Integer>> userBehaviorRedisTemplate(@Qualifier("userBehaviorRedisConnectionFactory") RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Map<String, Integer>> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Map.class));
        return template;
    }
}
用户行为服务实现类
java 复制代码
@Service
public class UserBehaviorServiceImpl implements UserBehaviorService {

    private static final long CACHE_EXPIRATION_DAYS = 1;
    private static final String CACHE_PREFIX = "articleCounts:";

    @Autowired
    private UserBehaviorMapper userBehaviorMapper;

    @Autowired
    @Qualifier("userBehaviorRedisTemplate")
    private RedisTemplate<String, Map<String, Integer>> userBehaviorRedisTemplate;

    @Override
    public void setLikeArticle(Likes likes) {
        likes.setCreateTime(LocalDateTime.now());
        Integer userId = ThreadLocalUtil.getUser("id");
        if (userId != null) {
            likes.setUserId(userId);
        }
        userBehaviorMapper.insertLike(likes);
    }

    @Override
    public void setFavoriteArticle(Favorites favorites) {
        favorites.setCreateTime(LocalDateTime.now());
        Integer userId = ThreadLocalUtil.getUser("id");
        if (userId != null) {
            favorites.setUserId(userId);
        }
        userBehaviorMapper.insertFavorite(favorites);
    }

    @Override
    public void setCommentArticle(Comments comments) {
        comments.setCreateTime(LocalDateTime.now());
        Integer userId = ThreadLocalUtil.getUser("id");
        if (userId != null) {
            comments.setUserId(userId);
        }
        userBehaviorMapper.insertComment(comments);
    }

    @Override
    public void setViewArticle(Views views) {
        views.setCreateTime(LocalDateTime.now());
        Integer userId = ThreadLocalUtil.getUser("id");
        if (userId != null) {
            views.setUserId(userId);
        }
        userBehaviorMapper.insertView(views);
    }

    @Override
    public Map<String, Integer> getArticleCounts(Integer articleId) {
        String key = CACHE_PREFIX + articleId;
        Map<String, Integer> counts = userBehaviorRedisTemplate.opsForValue().get(key);
        if (counts == null) {
            counts = fetchArticleCountsFromDB(articleId);
            cacheArticleCounts(articleId, counts);
        }
        return counts;
    }

    private Map<String, Integer> fetchArticleCountsFromDB(Integer articleId) {
        Map<String, Integer> counts = new HashMap<>();
        counts.put("likesCount", userBehaviorMapper.selectLikesCount(articleId));
        counts.put("favoritesCount", userBehaviorMapper.selectFavoritesCount(articleId));
        counts.put("commentsCount", userBehaviorMapper.selectCommentsCount(articleId));
        counts.put("viewsCount", userBehaviorMapper.selectViewsCount(articleId));
        return counts;
    }

    private void cacheArticleCounts(Integer articleId, Map<String, Integer> counts) {
        String key = CACHE_PREFIX + articleId;
        userBehaviorRedisTemplate.opsForValue().set(key, counts, CACHE_EXPIRATION_DAYS, TimeUnit.DAYS);
    }
}
Token拦截器
java 复制代码
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if (redisToken == null) {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }

            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.setUser(claims);
            return true;
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }

    @Override
    public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
相关推荐
时差95329 分钟前
【面试题】Hive 查询:如何查找用户连续三天登录的记录
大数据·数据库·hive·sql·面试·database
让学习成为一种生活方式31 分钟前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言
秋意钟1 小时前
MySQL日期类型选择建议
数据库·mysql
计算机-秋大田2 小时前
基于Spring Boot的船舶监造系统的设计与实现,LW+源码+讲解
java·论文阅读·spring boot·后端·vue
Dxy12393102162 小时前
python下载pdf
数据库·python·pdf
桀桀桀桀桀桀2 小时前
数据库中的用户管理和权限管理
数据库·mysql
代码之光_19803 小时前
保障性住房管理:SpringBoot技术优势分析
java·spring boot·后端
superman超哥3 小时前
04 深入 Oracle 并发世界:MVCC、锁、闩锁、事务隔离与并发性能优化的探索
数据库·oracle·性能优化·dba
用户8007165452003 小时前
HTAP数据库国产化改造技术可行性方案分析
数据库