ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 缓存 ## 说明 Zebra 集成了 CaffeineCache 和 Redis 作为 Spring Cache 的底层缓存实现,通过配置中心控制缓存的配置。 缓存分两种: * 一级缓存 :一级缓存为微服务实例(进程)内的缓存。 * 二级缓存 :使用 Redis 作为二级缓存,同个微服务的所有实例共享一个二级缓存。开启二级缓存后,每个微服务下的所有实例的一级缓存也会同步。 ## 开发 ### 引入依赖 ```markup <dependency> <groupId>com.guosen</groupId> <artifactId>zebra-cache</artifactId> <version>${zebra.version}</version> </dependency> ``` _注:将 ${zebra.version} 替换为使用的 Zebra 版本_ ### 代码 使用 Spring Cache 注解,在对应的接口函数上添加注解即可。 ```java public interface EchoService { @Cacheable(cacheNames={"myFirstCache"}) String echo(String value); @CacheEvict(cacheNames={"myFirstCache"}) String echoRemove(String value); @CacheEvict(allEntries = true, cacheNames={"myFirstCache"}) String echoClean(String value); @Cacheable(cacheNames={"mySecondaryCache"}) String echo2(String value); @CacheEvict(cacheNames={"mySecondaryCache"}) String echo2Remove(String value); } ``` ### 配置项 #### 配置样例 ```text zebra.cache.enable=true zebra.cache.enable.two=true cache.maximumSize=10000 cache.expire=1800000 zebra.cache.redis.topic=cache redis.database=0 redis.hostName=xxx.xxx.xxx.xxx redis.port=6410 redis.password=password redis.timeout=1000 redis.maxIdle=300 #redis.maxActive=600 redis.maxTotal=1000 redis.maxWaitMillis=1000 redis.minEvictableIdleTimeMillis=300000 redis.numTestsPerEvictionRun=1024 redis.timeBetweenEvictionRunsMillis=30000 redis.testOnBorrow=true redis.testWhileIdle=true redis.readTimeout=1000 ``` #### 配置说明 **基本配置** | 配置项 | 类型 | 说明 | | :--- | :--- | :--- | | zebra.cache.enable | Booean | 是否开启缓存 true : 开启 false:不开启 | | zebra.cache.enable.two | Boolean | 是否开启二级缓存 true:开启 false:不开启 | | cache.maximumSize | Integer | 缓存的最大数量 | | cache.expire | Integer | 缓存超期时间,单位:毫秒,默认为1800000 | | zebra.cache.redis.topic | String | 用于缓存变更通知的 Redis topic 名称 | | redis.database | Integer | Redis数据库 ID | | redis.hostName | String | Redis IP 或者域名 | | redis.port | Integer | Redis 端口号 | | redis.password | String | Redis 密码 | **高级配置** 以下配置项用于控制微服务实例和Redis的连接,一般使用默认值(即不配置)即可。 | 配置项 | 类型 | 说明 | | :--- | :--- | :--- | | redis.timeout | Integer | 客户端超时时间,单位:毫秒。默认值为 2000 | | redis.maxIdle | Integer | 最大空闲数 | | redis.maxActive | Integer | 连接池的最大数据库连接数。设为0表示无限制,如果是 Jedis 2.4 以后用redis.maxTotal | | redis.maxTotal | Integer | 控制一个 pool 可分配多少个jedis实例,用来替换上面的 redis.maxActive,如果是jedis 2.4以后用该属性 | | redis.maxWaitMillis | Integer | 最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。 | | redis.minEvictableIdleTimeMillis | Integer | 连接的最小空闲时间 默认 1800000 毫秒\( 30 分钟\) | | redis.numTestsPerEvictionRun | Integer | 每次释放连接的最大数目,默认 3 | | redis.timeBetweenEvictionRunsMillis | Integer | 逐出扫描的时间间隔\(毫秒\) 如果为负数,则不运行逐出线程, 默认-1 | | redis.testOnBorrow | Boolean | 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个 | | redis.testWhileIdle | Boolean | 在空闲时检查有效性,默认 false | | redis.readTimeout | Integer | 读取超时,单位:毫秒 |