springboot集成redis之接口缓存

什么是redis的接口缓存?

Redis的接口缓存是一种利用Redis这种内存数据库来存储接口(API)响应数据的技术,以提高应用程序的响应速度和性能。具体来说,当用户请求一个接口时,系统会首先检查Redis缓存中是否已经有了这个请求的响应数据。如果有,系统就直接从Redis中取出数据返回给用户,而不需要重新执行数据查询或计算的过程,这样可以显著减少响应时间和减轻后端数据库的负载。

基础

@Cacheable

  • value:缓存名称,指定缓存管理器中缓存的名称。可以指定一个或多个缓存名称,用于将方法的返回值存储在不同的缓存中。
  • cacheNames :与 value 属性类似,用于指定缓存名称。
  • key:缓存数据的键。默认情况下,Spring 会使用方法参数来生成键。也可以自定义键的生成策略。
  • keyGenerator:用于指定自定义的键生成器。
  • condition:满足条件时才缓存方法的结果。可以使用 SpEL 表达式。
  • unless:满足条件时方法的结果不会被缓存。也是使用 SpEL 表达式。
  • sync :如果设置为 true,则在缓存方法的结果时,将使用同步块来防止多个线程同时计算相同的结果。

代码实践

config

java 复制代码
package com.wyl.redis.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import net.sf.ehcache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author WuYiLong
 * @Date 2024/7/23 16:15
 */
@EnableCaching
@Configuration
public class CacheManagerConfig {

    @Primary
    @Bean
    public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory){
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .computePrefixWith(cacheName -> cacheName + ":")
                .entryTtl(Duration.ofMinutes(30))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisConfig.jackson2JsonRedisSerializer()));

        Map<String, RedisCacheConfiguration> configMap = new HashMap();
        configMap.put("redisCacheManager",redisCacheConfiguration);
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration, configMap);
        return redisCacheManager;
    }

    @Bean
    public CacheManager caffeineCacheManager() {
        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setCaffeine(Caffeine.newBuilder()
                .expireAfterWrite(Duration.ofMinutes(5))
                .initialCapacity(100)
                .maximumSize(200));
        return caffeineCacheManager;
    }

    @Bean
    public CacheManager ehCacheCacheManager() {
        EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager();
        net.sf.ehcache.CacheManager cacheManager = new net.sf.ehcache.CacheManager();
        Cache cache = new Cache("ehCache",200,false,false,300L,180L);
        cacheManager.addCacheIfAbsent(cache);
        ehCacheCacheManager.setCacheManager(cacheManager);
        return ehCacheCacheManager;
    }

}

service

java 复制代码
@Cacheable(value = "listFullCityByRedis",key = "'list'",unless = "#result == null ",cacheManager = "redisCacheManager")
    @Override
    public List<FullCityVo> listFullCityByRedis() {
        List<FullCity> fullCities = list();
        List<FullCityVo> fullCityVos = fullCities.stream().map(m -> {
            FullCityVo fullCityVo = new FullCityVo();
            BeanUtil.copyProperties(m, fullCityVo);
            return fullCityVo;
        }).collect(Collectors.toList());
        return fullCityVos;
    }

    @Cacheable(value = "listFullCityByCaffeine",key = "'list'",unless = "#result == null ",cacheManager = "caffeineCacheManager")
    @Override
    public List<FullCityVo> listFullCityByCaffeine() {
        List<FullCity> fullCities = list();
        List<FullCityVo> fullCityVos = fullCities.stream().map(m -> {
            FullCityVo fullCityVo = new FullCityVo();
            BeanUtil.copyProperties(m, fullCityVo);
            return fullCityVo;
        }).collect(Collectors.toList());
        return fullCityVos;
    }

    @Cacheable(value = "ehCache",key = "'list'",unless = "#result == null ",cacheManager = "ehCacheCacheManager")
    @Override
    public List<FullCityVo> listFullCityByEhCache() {
        List<FullCity> fullCities = list();
        List<FullCityVo> fullCityVos = fullCities.stream().map(m -> {
            FullCityVo fullCityVo = new FullCityVo();
            BeanUtil.copyProperties(m, fullCityVo);
            return fullCityVo;
        }).collect(Collectors.toList());
        return fullCityVos;
    }

controller

java 复制代码
    @ApiOperation(value = "列表-基于redis的缓存")
    @GetMapping(value = "listFullCityByRedis")
    public ResponseData<List<FullCityVo>> listFullCityByRedis() {
        return ResponseData.successInstance(fullCityService.listFullCityByRedis());
    }

    @ApiOperation(value = "列表-基于caffeine的缓存")
    @GetMapping(value = "listFullCityByCaffeine")
    public ResponseData<List<FullCityVo>> listFullCityByCaffeine() {
        return ResponseData.successInstance(fullCityService.listFullCityByCaffeine());
    }

    @ApiOperation(value = "列表-基于EhCache的缓存")
    @GetMapping(value = "listFullCityByEhCache")
    public ResponseData<List<FullCityVo>> listFullCityByEhCache() {
        return ResponseData.successInstance(fullCityService.listFullCityByEhCache());
    }

测试


项目说明

  • @EnableCaching:项目开启缓存功能
  • @CacheConfig:这个对整个类的方法有效

项目地址

github

相关推荐
自学也学好编程1 小时前
【数据库】Redis详解:内存数据库与缓存之王
数据库·redis
ChinaRainbowSea2 小时前
7. LangChain4j + 记忆缓存详细说明
java·数据库·redis·后端·缓存·langchain·ai编程
enjoy嚣士2 小时前
springboot 之 HTML与图片生成 (2)
spring boot·html转图片
白初&4 小时前
SpringBoot后端基础案例
java·spring boot·后端
鼠鼠我捏,要死了捏4 小时前
Redis缓存穿透、缓存击穿与雪崩防护及性能优化实战指南
redis·cache·performance
再睡亿分钟!4 小时前
Spring MVC 的常用注解
java·开发语言·spring boot·spring
麦兜*5 小时前
MongoDB 常见错误解决方案:从连接失败到主从同步问题
java·数据库·spring boot·redis·mongodb·容器
失散137 小时前
分布式专题——5 大厂Redis高并发缓存架构实战与性能优化
java·redis·分布式·缓存·架构
爱吃烤鸡翅的酸菜鱼9 小时前
【Spring】原理解析:Spring Boot 自动配置
java·spring boot
十八旬9 小时前
苍穹外卖项目实战(day7-1)-缓存菜品和缓存套餐功能-记录实战教程、问题的解决方法以及完整代码
java·数据库·spring boot·redis·缓存·spring cache