1 Star 6 Fork 1

不爱那么多I只爱一点点 / agile-cache

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

agile-cache : 缓存组件

它有什么作用

  • 二级缓存 自动实现耳机缓存同步,无需任何编码及复杂配置。ehcache作为一级缓存、redis作为二级缓存,默认二级缓存关闭

  • 统一操作方式 解析器通过提供CacheUtil、AgileCache,屏蔽掉各类型缓存介质的操作差异,以最简单的形式提供开发者开箱即用的缓存操作

  • 缓存过期 支持存储过程中直接设置缓存过期时间

  • 分布式/集群 通过redis发布订阅,自动完成一二级缓存同步与集群/分布式缓存同步操作

  • 并发操作 内部通过读写锁、乐观锁、锁粒度等方式,防止在一二级缓存同步过程中出现的并发问题,提高读写性能

  • 集合数据操作 CacheUtil、AgileCache针对不同存储介质提供一致性的集合数据操作API,参考快速入门

  • 支持Hibernate二级缓存 提供EhCache与Redis作为Hibernate二级缓存介质,并提供元数据形式的EhCache缓存配置方式。并且确保spring与hibernate二级缓存共享缓存管理器CacheManager

  • 支持缓存介质扩展 默认提供内存、EhCache、Redis三种缓存介质,开发人员可以根据实际需求,自行实现抽象类AgileCacheManager(缓存管理器抽象类)与AbstractAgileCache(缓存抽象类)并注入到spring容器中 实现方式非常简单


快速入门

开始你的第一个项目是非常容易的。

步骤 1: 下载包

您可以从[最新稳定版本]下载包(https://github.com/mydeathtrial/agile-cache/releases). 该包已上传至maven中央仓库,可在pom中直接声明引用

以版本agile-cache-2.1.0.M5.jar为例。

步骤 2: 添加maven依赖

<!--声明中央仓库-->
<repositories>
    <repository>
        <id>cent</id>
        <url>https://repo1.maven.org/maven2/</url>
    </repository>
</repositories>
        <!--声明依赖-->
<dependency>
<groupId>cloud.agileframework</groupId>
<artifactId>agile-cache</artifactId>
<version>2.1.0.M5</version>
</dependency>

步骤 3: 程序中调用CacheUtil(例)

public class YourClass {
    public void test() {
        /**
         * 添加缓存
         * @param key   缓存索引值,Object对象,一般使用字符串
         * @param value 缓存数据,Object对象,支持任意形式参数,当缓存介质为redis时,该对象需要实现序列化接口,以便存取过程中的正反序列化,redis默认使用JDK方式序列化该值
         **/
        CacheUtil.put("key", "value");

        /**
         * 如果不存在就存,存在就不存
         * @param key   缓存索引值,Object对象,一般使用字符串,缓存索引值
         * @param value 缓存数据,Object对象,支持任意形式参数,当缓存介质为redis时,该对象需要实现序列化接口,以便存取过程中的正反序列化,redis默认使用JDK方式序列化该值
         **/
        CacheUtil.putIfAbsent("key", "value");

        /**
         * 如果不存在就存,存在就不存
         * @param key     缓存索引值,Object对象,一般使用字符串,缓存索引值
         * @param value   缓存数据,Object对象,支持任意形式参数,当缓存介质为redis时,该对象需要实现序列化接口,以便存取过程中的正反序列化,redis默认使用JDK方式序列化该值
         * @param timeout 缓存过期时长,Duration对象,从存放时间点开始计算,过期后自动与缓存中清除该缓存数据
         **/
        CacheUtil.putIfAbsent("key", "value", Duration.ofHours(1));

        /**
         * 删除缓存
         * @param key   缓存索引值,Object对象,一般使用字符串,缓存索引值
         **/
        CacheUtil.evict("key");

        /**
         * 清空公共区域缓存
         **/
        CacheUtil.clear();

        /**
         * 判断缓存是否存在,true存在,false不存在
         * @param key   缓存索引值,Object对象,一般使用字符串,缓存索引值
         **/
        boolean isHave = CacheUtil.containKey("key");

        /**
         * 取缓存
         * @param key   缓存索引值,Object对象,一般使用字符串,缓存索引值
         * @param value 缓存数据类型,Class对象,用于取值后的反序列化过程,该值支持复杂数据类型
         **/
        CacheUtil.get("key", Integer.class);

        /**
         * 向Map中添加数据,方法调用前需要确保缓存中已经存放过key值为mapKey,value为Map结果的数据。
         *
         * @param mapKey 缓存索引,缓存解析器会根据mapKey于缓存中查找对应的Map结构缓存,取出后操作存储
         * @param key    map结构中的key无类型限制
         * @param value  map结构中的value无类型限制
         */
        CacheUtil.addToMap("mapKey", "key", "value");

        /**
         * 取缓存
         * @param mapKey 缓存索引,缓存解析器会根据mapKey于缓存中查找对应的Map结构缓存,取出后操作取值
         * @param key    map结构中的key,一般使用字符串
         * @param class  map结构中的value缓存数据类型,Class对象,用于取值后的反序列化过程,该值支持复杂数据类型
         **/
        Integer value = CacheUtil.getFromMap("mapKey", "key", Integer.class);

        /**
         * 从Map中删除数据,方法调用前需要确保缓存中已经存放过key值为mapKey,value为Map结果的数据。
         *
         * @param mapKey 缓存索引,缓存解析器会根据mapKey于缓存中查找对应的Map结构缓存,取出后操作存储
         * @param key    map结构中的key无类型限制
         */
        CacheUtil.removeFromMap("mapKey", "key");

        /**
         * 向List中添加数据,方法调用前需要确保缓存中已经存放过key值为listKey,value为List结构的数据。
         *
         * @param listKey 缓存索引,缓存解析器会根据listKey于缓存中查找对应的List结构缓存,取出后操作存储
         * @param node    List结构中的node无类型限制
         */
        CacheUtil.addToList("listKey", "node");

        /**
         * 从List中取数据,方法调用前需要确保缓存中已经存放过key值为listKey,value为List结构的数据。
         *
         * @param listKey 缓存索引,缓存解析器会根据listKey于缓存中查找对应的List结构缓存,取出后操作取值
         * @param index   List结构中的node下标
         * @param class  map结构中的value缓存数据类型,Class对象,用于取值后的反序列化过程,该值支持复杂数据类型
         **/
        Integer value = CacheUtil.getFromList("listKey", 2, Integer.class);

        /**
         * 从List中删除数据,方法调用前需要确保缓存中已经存放过key值为listKey,value为List结构的数据。
         *
         * @param listKey 缓存索引,缓存解析器会根据listKey于缓存中查找对应的List结构缓存,取出后操作取值
         * @param index   List结构中的node下标
         */
        CacheUtil.removeFromList("mapKey", 2);

        /**
         * 向Set中添加数据,方法调用前需要确保缓存中已经存放过key值为setKey,value为Set结构的数据。
         *
         * @param setKey  缓存索引,缓存解析器会根据setKey于缓存中查找对应的Set结构缓存,取出后操作存储
         * @param node    Set结构中的node无类型限制
         */
        CacheUtil.addToSet("setKey", "node");

        /**
         * 向Set中删除数据,方法调用前需要确保缓存中已经存放过key值为setKey,value为Set结构的数据。
         *
         * @param setKey  缓存索引,缓存解析器会根据setKey于缓存中查找对应的Set结构缓存
         * @param node    Set结构中的node无类型限制
         */
        CacheUtil.removeFromSet("setKey", "node");

        /**
         * 分布式/集群同步锁,仅当缓存介质为redis情况下,该锁有使用价值,一般用于集群、分布式同步锁,如集群任务调度
         *
         * @param lockName 锁标识
         * @return 是否加锁成功
         */
        boolean isSuccess = CacheUtil.lock("lockName");

        /**
         * 过期分布式/集群同步锁,仅当缓存介质为redis情况下,该锁有使用价值,一般用于集群、分布式同步锁,如集群任务调度
         *
         * @param lockName 锁标识
         * @param timeout  锁过期时长,Duration对象,从存放时间点开始计算,过期后自动解锁
         * @return 是否加锁成功
         */
        boolean isSuccess = CacheUtil.lock("lockName", Duration.ofHours(1));

        /**
         * 分布式/集群同步锁立即解锁,仅当缓存介质为redis情况下,该锁有使用价值,一般用于集群、分布式同步锁,如集群任务调度
         *
         * @param lockName 锁标识
         */
        CacheUtil.unlock("lockName");

        /**
         * 过期分布式/集群同步锁延迟解锁,仅当缓存介质为redis情况下,该锁有使用价值,一般用于集群、分布式同步锁,如集群任务调度
         *
         * @param lockName 锁标识
         * @param timeout  锁过期时长,从调用时间点开始计算,过期后自动解锁
         * @return 是否加锁成功
         */
        CacheUtil.unlock("lockName", Duration.ofHours(1));
    }
}

步骤 4: 缓存域

缓存分为若干区域,各缓存域间独立存取,互不干扰,程序默认缓存域为common-cache,CacheUtil工具中提供的默认方法均为直接操作默认缓存域 除默认缓存域外,开发人员可通过CacheUtil.getCache自行创建或使用自定义缓存域。缓存域也被大量用于Hibernate二级缓存。使用方法如下:

public class YourClass {
    public void region(){
        // 获取名为customRegionName的缓存域,当该域不存在时,系统自行创建
        AgileCache customRegionCache = CacheUtil.getCache("customRegionName");
        
        // 直接操作缓存域内缓存,AgileCache均提供同CacheUtil一致的缓存操作方法,使用方法可直接参照CacheUtil
        Integer cacheValue = customRegionCache.get("cacheKey",Integer.class);
    }
}

EhCache缓存配置

解析器中涵盖的EhCache解析器提供yml或properties形式配置,配置项与EhCache官方标准名一致,以默认公共缓存域common-cache为例:

//缓存组件启用开关
spring.ehcache.enabled=true

//开启redis二级缓存同步开关
spring.ehcache.sync=true

spring.ehcache.default-config-name=common-cache
spring.ehcache.path=/temp
spring.ehcache.regions.common-cache.max-entries-local-heap=10000
spring.ehcache.regions.common-cache.max-entries-local-disk=10000000
spring.ehcache.regions.common-cache.time-to-idle-seconds=0
spring.ehcache.regions.common-cache.time-to-live-seconds=0
spring.ehcache.regions.common-cache.disk-spool-buffer-size-m-b=30
spring.ehcache.regions.common-cache.eternal=false
spring.ehcache.regions.common-cache.memory-store-eviction-policy=LRU
spring.ehcache.regions.common-cache.disk-expiry-thread-interval-seconds=120

Redis缓存配置

使用spring-data-redis原生配置即可,例:

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=123456
spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.shutdown-timeout=100ms
spring.redis.ssl=false
spring.redis.database=0
spring.redis.timeout=60s

Hibernate二级缓存

缓存解析器默认提供EhCache与Redis作为Hibernate二级缓存介质,缓存域工厂类如下:

  • EhCache cloud.agileframework.cache.support.ehcache.EhCacheRegionFactory
  • Redis cloud.agileframework.cache.support.redis.RedisRegionFactory

spring-data-jpa中配置如下:

spring:
  jpa:
    database-platform: org.hibernate.dialect.MySQLDialect
    generate-ddl: false
    hibernate:
      ddl-auto: none
      naming:
        implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
    show-sql: false
    properties:
      hibernate:
        use_sql_comments: false
        format_sql: true
        cache:
          region_prefix: hibernate
          use_second_level_cache: true
          use_query_cache: true
          use_structured_entries: false
          hbm2ddl:
            auto: update
          region:
            factory_class: cloud.agileframework.cache.support.redis.RedisRegionFactory
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

Agile系列框架-缓存组件 缓存切换 切换方式与spring boot cache切换方式一致,均使用元数据spring.cache.type进行配置,当不存在该配置情况下,默认使用内存介质 统一操作方式 解析器通过提供CacheUtil、AgileCache,屏蔽掉各类型缓存介质的操作差异,以最简单的形式提供开发者开箱即用的缓存操作 缓存过期 支持存储过程中直接设置缓存过期时间 分布式/集群锁 当缓存介质为redis时,通过CacheUtil或AgileCache的lock与unlock提供锁操作 集合数据操作 CacheUtil、AgileCache针对不同存储介质提供一致性的集合数据操作API,参考快速入门 支持Hibernate二级缓存 提供EhCache与Red... 展开 收起
Java
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/agile-framework/agile-cache.git
git@gitee.com:agile-framework/agile-cache.git
agile-framework
agile-cache
agile-cache
master

搜索帮助