springboot集成redis之接口缓存

WuYiLong原创大约 3 分钟代码编程springbootredis

什么是redis的接口缓存?

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

基础

@Cacheable

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

代码实践

config

 1package com.wyl.redis.config;
 2
 3import com.github.benmanes.caffeine.cache.Caffeine;
 4import net.sf.ehcache.Cache;
 5import org.springframework.cache.CacheManager;
 6import org.springframework.cache.annotation.EnableCaching;
 7import org.springframework.cache.caffeine.CaffeineCacheManager;
 8import org.springframework.cache.ehcache.EhCacheCacheManager;
 9import org.springframework.context.annotation.Bean;
10import org.springframework.context.annotation.Configuration;
11import org.springframework.context.annotation.Primary;
12import org.springframework.data.redis.cache.RedisCacheConfiguration;
13import org.springframework.data.redis.cache.RedisCacheManager;
14import org.springframework.data.redis.cache.RedisCacheWriter;
15import org.springframework.data.redis.connection.RedisConnectionFactory;
16import org.springframework.data.redis.serializer.RedisSerializationContext;
17import org.springframework.data.redis.serializer.RedisSerializer;
18
19import java.time.Duration;
20import java.util.HashMap;
21import java.util.Map;
22
23/**
24 * @Description
25 * @Author WuYiLong
26 * @Date 2024/7/23 16:15
27 */
28@EnableCaching
29@Configuration
30public class CacheManagerConfig {
31
32    @Primary
33    @Bean
34    public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory){
35        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
36                .computePrefixWith(cacheName -> cacheName + ":")
37                .entryTtl(Duration.ofMinutes(30))
38                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()))
39                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisConfig.jackson2JsonRedisSerializer()));
40
41        Map<String, RedisCacheConfiguration> configMap = new HashMap();
42        configMap.put("redisCacheManager",redisCacheConfiguration);
43        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
44        RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration, configMap);
45        return redisCacheManager;
46    }
47
48    @Bean
49    public CacheManager caffeineCacheManager() {
50        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
51        caffeineCacheManager.setCaffeine(Caffeine.newBuilder()
52                .expireAfterWrite(Duration.ofMinutes(5))
53                .initialCapacity(100)
54                .maximumSize(200));
55        return caffeineCacheManager;
56    }
57
58    @Bean
59    public CacheManager ehCacheCacheManager() {
60        EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager();
61        net.sf.ehcache.CacheManager cacheManager = new net.sf.ehcache.CacheManager();
62        Cache cache = new Cache("ehCache",200,false,false,300L,180L);
63        cacheManager.addCacheIfAbsent(cache);
64        ehCacheCacheManager.setCacheManager(cacheManager);
65        return ehCacheCacheManager;
66    }
67
68}

service

 1@Cacheable(value = "listFullCityByRedis",key = "'list'",unless = "#result == null ",cacheManager = "redisCacheManager")
 2    @Override
 3    public List<FullCityVo> listFullCityByRedis() {
 4        List<FullCity> fullCities = list();
 5        List<FullCityVo> fullCityVos = fullCities.stream().map(m -> {
 6            FullCityVo fullCityVo = new FullCityVo();
 7            BeanUtil.copyProperties(m, fullCityVo);
 8            return fullCityVo;
 9        }).collect(Collectors.toList());
10        return fullCityVos;
11    }
12
13    @Cacheable(value = "listFullCityByCaffeine",key = "'list'",unless = "#result == null ",cacheManager = "caffeineCacheManager")
14    @Override
15    public List<FullCityVo> listFullCityByCaffeine() {
16        List<FullCity> fullCities = list();
17        List<FullCityVo> fullCityVos = fullCities.stream().map(m -> {
18            FullCityVo fullCityVo = new FullCityVo();
19            BeanUtil.copyProperties(m, fullCityVo);
20            return fullCityVo;
21        }).collect(Collectors.toList());
22        return fullCityVos;
23    }
24
25    @Cacheable(value = "ehCache",key = "'list'",unless = "#result == null ",cacheManager = "ehCacheCacheManager")
26    @Override
27    public List<FullCityVo> listFullCityByEhCache() {
28        List<FullCity> fullCities = list();
29        List<FullCityVo> fullCityVos = fullCities.stream().map(m -> {
30            FullCityVo fullCityVo = new FullCityVo();
31            BeanUtil.copyProperties(m, fullCityVo);
32            return fullCityVo;
33        }).collect(Collectors.toList());
34        return fullCityVos;
35    }

controller

 1    @ApiOperation(value = "列表-基于redis的缓存")
 2    @GetMapping(value = "listFullCityByRedis")
 3    public ResponseData<List<FullCityVo>> listFullCityByRedis() {
 4        return ResponseData.successInstance(fullCityService.listFullCityByRedis());
 5    }
 6
 7    @ApiOperation(value = "列表-基于caffeine的缓存")
 8    @GetMapping(value = "listFullCityByCaffeine")
 9    public ResponseData<List<FullCityVo>> listFullCityByCaffeine() {
10        return ResponseData.successInstance(fullCityService.listFullCityByCaffeine());
11    }
12
13    @ApiOperation(value = "列表-基于EhCache的缓存")
14    @GetMapping(value = "listFullCityByEhCache")
15    public ResponseData<List<FullCityVo>> listFullCityByEhCache() {
16        return ResponseData.successInstance(fullCityService.listFullCityByEhCache());
17    }

测试

image.png

image.png

项目说明

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

项目地址

githubopen in new window

上次编辑于:
贡献者: wuyilong