redis缓存工具类【当缓存未命中时,自动调用数据加载函数从数据库获取数据并存入Redis】

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.function.Supplier;

@Service
public class CacheService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 通用缓存获取方法
     * @param cacheKey 缓存键
     * @param dataLoader 数据加载器函数
     * @return 缓存或数据库中的数据
     */
    public <T> T getFromCache(String cacheKey, Supplier<T> dataLoader) {
        // 从缓存获取数据
        T data = (T) redisTemplate.opsForValue().get(cacheKey);

        if (data != null) {
            return data;
        }

        // 缓存未命中,加载数据
        data = dataLoader.get();

        if (data != null) {
            // 放入缓存(永不过期)
            redisTemplate.opsForValue().set(cacheKey, data);
        }

        return data;
    }
}
java 复制代码
@Configuration
public class RedisTemplateConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
    // 配置消息监听器容器
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }
}

使用

java 复制代码
@Override
	@GetMapping(SELECTLIST)
	public R<List<MpBannerEntity>> selectMpBannerList() {
		String cacheKey = CacheConstant.MP_BANNERS;

		List<MpBannerEntity> list = cacheService.getFromCache(cacheKey, () ->
				mpBannerService.list(Wrappers.<MpBannerEntity>query().lambda()
						.eq(MpBannerEntity::getStatus, 2)
						.orderByAsc(MpBannerEntity::getSno))
		);

		return R.data(list);
	}

通过自定义CacheService类提供通用缓存获取方法,结合RedisTemplate实现数据缓存功能。当缓存未命中时,自动调用数据加载函数从数据库获取数据并存入Redis。配置类RedisTemplateConfig设置了键值序列化方式,并初始化了Redis消息监听容器。实际应用示例展示了如何通过注解方式查询轮播图数据,实现"缓存优先"的访问模式,显著提升系统性能。这套方案具有通用性强、使用简便的特点,适用于各类需要缓存加速的业务场景。

相关推荐
先睡6 小时前
Redis的缓存击穿和缓存雪崩
redis·spring·缓存
weixin_446122469 小时前
JAVA内存区域划分
java·开发语言·redis
TT哇9 小时前
JavaEE==网站开发
java·redis·java-ee
Bug退退退12310 小时前
RabbitMQ 高级特性之死信队列
java·分布式·spring·rabbitmq
qq_3923971211 小时前
Redis常用操作
数据库·redis·wpf
一只叫煤球的猫13 小时前
真实事故复盘:Redis分布式锁居然失效了?公司十年老程序员踩的坑
java·redis·后端
booooooty16 小时前
基于Spring AI Alibaba的多智能体RAG应用
java·人工智能·spring·多智能体·rag·spring ai·ai alibaba
极光雨雨16 小时前
Spring Bean 控制销毁顺序的方法总结
java·spring
Spirit_NKlaus16 小时前
解决HttpServletRequest无法获取@RequestBody修饰的参数
java·spring boot·spring
lwb_011817 小时前
SpringCloud——Gateway新一代网关
spring·spring cloud·gateway