SpringBoot中Cache实现

本地版说明

  • springboot 2.6.6

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>

主启动类,开启Spring Cache

package gk.springboot.preheat;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching  // 主启动类,开启Spring Cache
@MapperScan(basePackages = "gk.springboot.preheat.dao")
public class SpringBootPreheatApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootPreheatApplication.class, args);
    }
}

基于Caffeine本地缓存 或 Redis实现

  • Caffeine是SpringBoot 2.x后支持的本地缓存,不再支持Guava
  • CacheManager中有一个属性cacheMap,将数据存储在ConcurrentHashMap中(即JVM中)
  • 这也是为什么下面配置caffeineCacheManager时,将缓存key和value设置为弱引用(可以防止缓存不过期导致的OOM)
 public class CaffeineCacheManager implements CacheManager {

	private Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder();

	@Nullable
	private CacheLoader<Object, Object> cacheLoader;

	private boolean allowNullValues = true;

	private boolean dynamic = true;

	private final Map<String, Cache> cacheMap = new ConcurrentHashMap<>(16);

	private final Collection<String> customCacheNames = new CopyOnWriteArrayList<>();

  • 配置Cache的CacheManager
package gk.springboot.preheat.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Configuration
public class CacheManagerConfig {
    // 缓存过期时间,单位是通过TimeUnit设置
    private long expire = 5;
    // 缓存底层ConcurrentHashMap的初始化容量
    private int initialCapacity = 16;
    // ConcurrentHashMap最大容量,当超过该容量时,默认采用LRU算法淘汰
    private long maximumSize = 1024;
    // 自动刷新缓存的间隔时间

    /**
     * 使用 Caffeine 作为底层缓存容器
     * Caffeine官网地址:https://github.com/ben-manes/caffeine/wiki/Home-zh-CN
     * 快速上手见:https://juejin.cn/post/7067090649245286408#heading-6
     */
    @Bean("caffeineCacheManager")
    @Primary    // 由于Spring容器中实现了2个CacheManager,故需要设置一个主CacheManager
    public CacheManager caffeineCacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(
                Caffeine.newBuilder()
                        .expireAfterWrite(expire, TimeUnit.MINUTES)
                        .initialCapacity(initialCapacity)
                        .maximumSize(maximumSize)
                        .weakKeys() // 将缓存key设置为弱引用
                        .weakValues()   // 将缓存value设置为弱引用
        );
        return cacheManager;
    }


    /**
     * 使用Redis作为底层缓存容器
     */
    @Bean("redisCacheManager")
    public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .disableCachingNullValues()
                .entryTtl(Duration.ofMinutes(expire))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
        return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(redisCacheConfiguration).build();
    }
}

测试并查看

package gk.springboot.preheat.controller;

import gk.springboot.preheat.model.UserInfo;
import gk.springboot.preheat.service.UserService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user/")
public class UserController {
    @Resource
    private UserService userService;


    @GetMapping("getById")
    @Cacheable(value = "users",key = "#id",cacheManager = "caffeineCacheManager")
    public UserInfo getUserById(@RequestParam("id") Integer id) {
        System.out.println("未命中缓存,调用userService方法");
        return userService.getUserById(id);
    }

    @GetMapping("getById2")
    @Cacheable(value = "users",key = "#id",cacheManager = "redisCacheManager")
    public UserInfo getUserById2(@RequestParam("id") Integer id) {
        System.out.println("未命中缓存,调用userService方法");
        return userService.getUserById(id);
    }
}
  • 通过请求 getById2后,可以在redis中看到被缓存的数据
    redis中的数据
  • 请求getById后,未命中Caffeine本地缓存,则走数据库,否则从JVM中获取数据
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值