缓存详解-在java项目中使用缓存,最主流的缓存caffeine+redisson

概述

在java项目中经常有使用缓存的场景,这时候如何使用缓存就很重要了,本文主要介绍spring缓存的选型和实现

什么是合格的缓存

一般业务缓存需要满足最低的条件是:
1.有边界,能定义缓存的大小
2.有过期时间
3.有合理的缓存淘汰策略

缓存选型

毫无疑问本地缓存最合适最强大的是caffeine,功能强大,应用广泛。
在外部缓存中,redis是比较常用的一个中间件,本身也实现了多种缓存淘汰策略,但是redis作为缓存,太重量级了,需要一整个redis实例作为缓存,并不轻量级。好在有redission这个工具在,redisson使用lua脚本实现了在redis上的有边界的缓存,并实现了过期时间,空闲等待时间,淘汰策略等。

spring多缓存实现

一个项目中,一般至少会用到本地缓存和redis缓存,所以这里按照上面的选型,使用caffeine+redisson来搭建
配置代码非常简单,只需要一个类就完成了。

先引入maven依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.5.7</version>
        </dependency>
        

下面是java的配置代码

package com.example.demo.web.vo;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.spring.cache.CacheConfig;
import org.redisson.spring.cache.RedissonSpringCacheManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author qiupengjun
 * @Date 2022 11 01 16 33
 **/
@Configuration
public class CommonCacheConfig {
    @Value("${spring.redis.port:0}")
    private int redisPort;
    @Value("${spring.redis.database:0}")
    private int redisDb;
    @Value("${spring.redis.host:0}")
    private String redisHost;
    @Value("${spring.redis.timeout:0}")
    private int redisTimeOut;
    @Value("${spring.redis.password:0}")
    private String redisPassword;
    private enum Caches {
        CAFFEINE_TEST_CACHE(2, 600,300),
        CAFFEINE_TEST_CACHE_1(20, 1800,900),
        REDIS_TEST_CACHE(2, 600,300),
        REDIS_TEST_CACHE_1(20, 1800,900),
        ;
        /** 最大数量*/
        private final Integer maxSize;
        /** 过期时间 秒*/
        private final Integer ttl;
        /** 最大空闲时间 秒 */
        private Integer maxIdle;
        Caches(Integer maxSize, Integer ttl,Integer maxIdle) {
            this.maxIdle = maxIdle;
            this.maxSize = maxSize;
            this.ttl = ttl;
        }
        Caches(Integer maxSize, Integer ttl) {
            this.maxSize = maxSize;
            this.ttl = ttl;
        }
    }

    @Bean("CAFFEINE_MANAGER")
    @Primary
    public CacheManager buildCaffeineCacheManager() {
        SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
        ArrayList<CaffeineCache> caffeineCaches = new ArrayList<>();
        for (Caches c : Caches.values()) {
            if(c.name().startsWith("CAFFEINE_")){
                caffeineCaches.add(new CaffeineCache(c.name(),
                                Caffeine.newBuilder()
                                        .recordStats()
                                        .expireAfterWrite(c.ttl, TimeUnit.SECONDS)
                                        .expireAfterAccess(c.maxIdle, TimeUnit.SECONDS)
                                        .maximumSize(c.maxSize)
                                        .build()
                        )
                );
            }
        }

        simpleCacheManager.setCaches(caffeineCaches);
        return simpleCacheManager;
    }

    @Bean(destroyMethod = "shutdown")
    RedissonClient redisson(){
        Config config = new Config();
        //这里使用你的redis地址 以及redis的密码 和redis要存储的数据库
        config.useSingleServer()
                .setAddress("redis://"+redisHost+":"+redisPort)
                .setTimeout(redisTimeOut)
                .setPassword(redisPassword)
                .setDatabase(redisDb);
        return Redisson.create(config);
    }

    @Bean("REDISSON_MANAGER")
    CacheManager cacheManager(RedissonClient redissonClient) {
        Map<String, CacheConfig> config = new HashMap<>();
        for (Caches c : Caches.values()) {
            if(c.name().startsWith("REDIS_")){
                //这里要注意单位
                CacheConfig cacheConfig = new CacheConfig(c.ttl*1000,c.maxIdle*1000);
                cacheConfig.setMaxSize(c.maxSize);
                config.put(c.name(),cacheConfig);
            }
        }
        return new RedissonSpringCacheManager(redissonClient, config);
    }
}


可以看到这里有两个cacheManager的bean,分别对应redisson缓存和caffeine缓存,在Spring里面使用多cacheManager,默认使用带@Primary注释的缓存,同时可以通过注解@Cacheable里的cacheManager字段来指定使用缓存。

在这个示例中,我把缓存类型配置放在了enum Caches 这个枚举内部类中,CAFFEINE_开头的会在caffeine的cacheManager里面初始化,REDIS_开头的会在caffeine的cacheManager里面初始化,他们包含了例如最大数量、过期时间、空闲时间(最后一次读)等参数。然后把枚举的名称注册为缓存名。在使用例如@Cacheable类型的缓存注解,字段cacheNames声明要使用的缓存类型,比如如果使用REDIS_TEST_CACHE,那按配置,缓存最大数量为2,过期时间600s,300s没读取过这个缓存则会去除,如果使用REDIS_TEST_CACHE_1,那按配置,缓存最大数量为20,过期时间1800s,900s没读取过这个缓存则会去除。
示例如下:

  @Cacheable(cacheNames = "REDIS_TEST_CACHE", key = "#root.methodName+':'+#paramTest",cacheManager = "REDISSON_MANAGER")
  public String testCacheRedis(String paramTest){
    return System.currentTimeMillis()+paramTest;
  }
  @Cacheable(cacheNames = "CAFFEINE_TEST_CACHE", key = "#root.methodName+':'+#paramTest",cacheManager = "CAFFEINE_MANAGER")
  public String testCacheCaffeine(String paramTest){
    return System.currentTimeMillis()+paramTest;
  }

在本示例里面cache的关系基本如下图,通过指定cacheNames和cacheManager来使用缓存
image.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值