1.4K Star 4.9K Fork 1.7K

GVP红薯 / J2Cache

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

J2Cache

J2Cache —— 基于内存和 Redis 的两级 Java 缓存框架

JavaDoc https://apidoc.gitee.com/ld/J2Cache/

J2Cache 是 OSChina 目前正在使用的两级缓存框架(要求至少 Java 8)。第一级缓存使用内存(同时支持 Ehcache 2.x、Ehcache 3.x 和 Caffeine),第二级缓存使用 Redis(推荐)/Memcached 。 由于大量的缓存读取会导致 L2 的网络成为整个系统的瓶颈,因此 L1 的目标是降低对 L2 的读取次数。 该缓存框架主要用于集群环境中。单机也可使用,用于避免应用重启导致的缓存冷启动后对后端业务的冲击。

J2Cache 相关文章:

J2Cache 已经有 Python 语言版本了,详情请看 https://gitee.com/ld/Py3Cache

J2Cache 从 1.3.0 版本开始支持 JGroups 和 Redis Pub/Sub 两种方式进行缓存事件的通知。在某些云平台上可能无法使用 JGroups 组播方式,可以采用 Redis 发布订阅的方式。详情请看 j2cache.properties 配置文件的说明。

视频介绍:http://v.youku.com/v_show/id_XNzAzMTY5MjUy.html

J2Cache 的两级缓存结构

L1: 进程内缓存(caffeine\ehcache)
L2: Redis/Memcached 集中式缓存

数据读取

  1. 读取顺序 -> L1 -> L2 -> DB

  2. 数据更新

    1 从数据库中读取最新数据,依次更新 L1 -> L2 ,发送广播清除某个缓存信息
    2 接收到广播(手工清除缓存 & 一级缓存自动失效),从 L1 中清除指定的缓存信息

J2Cache 配置

配置文件位于 core/resources 目录下,包含三个文件:

  • j2cache.properties J2Cache 核心配置文件,可配置两级的缓存,Redis 服务器、连接池以及缓存广播的方式
  • caffeine.properties 如果一级缓存选用 Caffeine ,那么该文件用来配置缓存信息
  • ehcache.xml Ehcache 的配置文件,配置说明请参考 Ehcache 文档
  • ehcache3.xml Ehcache3 的配置文件,配置说明请参考 Ehcache 文档
  • network.xml JGroups 网络配置,如果使用 JGroups 组播的话需要这个文件,一般无需修改

实际使用过程需要将所需的配置文件复制到应用类路径中,如 WEB-INF/classes 目录。

J2Cache 运行时所需 jar 包请查看 core/pom.xml

测试方法

  1. 安装 Redis
  2. git clone https://gitee.com/ld/J2Cache
  3. 修改 core/resource/j2cache.properties 配置使用已安装的 Redis 服务器
  4. 在命令行中执行 mvn package -DskipTests=true 进行项目编译
  5. 打开多个命令行窗口,同时运行 runtest.sh
  6. 在 > 提示符后输入 help 查看命令,并进行测试

示例代码

详细的使用方法请看 J2CacheCmd.java

与spring cache 集成 SpringCache 集成 J2Cache 配置案例

使用方法

J2Cache 默认使用 Caffeine 作为一级缓存,使用 Redis 作为二级缓存。你还可以选择 Ehcache2 和 Ehcache3 作为一级缓存。

准备工作

  1. 安装 Redis
  2. 新建一个基于 Maven 的 Java 项目

一. 引用 Maven

<dependency>
  <groupId>net.oschina.j2cache</groupId>  
  <artifactId>j2cache-core</artifactId>  
  <version>xxxxx</version>  
</dependency>

中央仓库地址:>>飞机

二. 准备配置

拷贝 j2cache.propertiescaffeine.properties 到你项目的源码目录,并确保这些文件会被编译到项目的 classpath 中。如果你选择了 ehcache 作为一级缓存,需要拷贝 ehcache.xml 或者 ehcache3.xml 到源码目录(后者对应的是 Ehcache 3.x 版本),这些配置文件的模板可以从 https://gitee.com/ld/J2Cache/tree/master/core/resources 这里获取。

使用你喜欢的文本编辑器打开 j2cache.properties 并找到 redis.hosts 项,将其信息改成你的 Redis 服务器所在的地址和端口。

我们建议缓存在使用之前都需要预先设定好缓存大小及有效时间,使用文本编辑器打开 caffeine.properties 进行缓存配置,配置方法请参考文件中的注释内容。

例如:default = 1000,30m #定义缓存名 default ,对象大小 1000,缓存数据有效时间 30 分钟。 你可以定义多个不同名称的缓存。

三. 编写代码

Test.java

public static void main(String[] args) {
    CacheChannel cache = J2Cache.getChannel();
    
    //缓存操作
    cache.set("default", "1", "Hello J2Cache");
    System.out.println(cache.get("default", "1"));
    cache.evict("default", "1");
    System.out.println(cache.get("default", "1"));
    
    cache.close();
}

编译并运行查看结果,更多的用法请参考 CacheChannel.java 接口的方法。

请注意 cache.close() 方法只需在程序退出时调用。

四. 动态构建 J2Cache 实例

J2CacheConfig config = new J2CacheConfig();
//填充 config 变量所需的配置信息
J2CacheBuilder builder = J2CacheBuilder.init(config);
CacheChannel channel = builder.getChannel();
//进行缓存的操作
channel.close();

五. 集群测试

为了方便测试集群模式下 J2Cache 的运行,我们提供了一个命令行小程序,请参考此页面前面的 “测试方法”

常见问题

  1. J2Cache 的使用场景是什么?
    首先你的应用是运行在集群环境,使用 J2Cache 可以有效降低节点间的数据传输量;其次单节点使用 J2Cache 可以避免应用重启后对后端业务系统的冲击

  2. 为什么不能在程序中设置缓存的有效期
    在程序中定义缓存数据的有效期会导致缓存不可控,一旦数据出问题无从查起,因此 J2Cache 的所有缓存的有效期都必须在 一级缓存 的配置中预设好再使用

  3. 如何使用 JGroups 组播方式(无法在云主机中使用)
    首先修改 j2cache.properties 中的 j2cache.broadcast 值为 jgroups,然后在 maven 中引入

    <dependency>
        <groupId>org.jgroups</groupId>
        <artifactId>jgroups</artifactId>
        <version>3.6.13.Final</version>
    </dependency>
  4. 如何使用 ehcache 作为一级缓存
    首先修改 j2cache.properties 中的 j2cache.L1.provider_class 为 ehcache 或者 ehcache3,然后拷贝 ehcache.xml 或者 ehcache3.xml 到类路径,并配置好缓存,需要在项目中引入对 ehcache 的支持:

    <dependency><!-- Ehcache 2.x //-->
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.10.4</version>
    </dependency>
    
    <dependency><!-- Ehcache 3.x //-->
        <groupId>org.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>3.4.0</version>
    </dependency>
    
  5. 如何使用 RabbitMQ 作为消息通知
    首先修改 j2cache.properties 中的 j2cache.broadcast 为 rabbitmq,然后在 j2cache.properties 中配置 rabbitmq.xxx 相关信息。

    需要在项目中引入对 rabbitmq 的支持:

    <dependency>
        <groupId>com.rabbitmq</groupId>
        <artifactId>amqp-client</artifactId>
        <version>5.3.0</version>
    </dependency>
  6. 如何使用 RocketMQ 作为消息通知
    首先修改 j2cache.properties 中的 j2cache.broadcast 为 rocketmq,然后在 j2cache.properties 中配置 rocketmq.xxx 相关信息。

    需要在项目中引入对 rabbitmq 的支持:

    <dependency>
        <groupId>org.apache.rocketmq</groupId>
        <artifactId>rocketmq-client</artifactId>
        <version>4.3.0</version>
        <scope>provided</scope>
    </dependency>
  7. 如何使用 memcached 作为二级缓存
    首先修改 j2cache.properties 中的 j2cache.L2.provider_class 为 memcached,然后在 j2cache.properties 中配置 memcached.xxx 相关信息。

    需要在项目中引入对 memcached 的支持:

    <dependency>
        <groupId>com.googlecode.xmemcached</groupId>
        <artifactId>xmemcached</artifactId>
        <version>2.4.5</version>
    </dependency>
  8. 为什么 J2Cache 初始化时,连接本机的 Redis 非常慢,要 5 秒以上?

    如果出现这种情况,请在系统 hosts 里配置机器名和IP地址的对应关系,例如:

    127.0.0.1       localhost
    127.0.0.1       winter-notebook.local
    ::1             localhost
    ::1             winter-notebook.local
  9. 使用何种 Redis 的存储模式最佳? generic 还是 hash ?

    我们推荐使用 generic 存储模式,这也是 J2Cache 默认的存储模式,hash 模式最大的问题是无法单独对 key 进行 expire 设置。

哪些项目在用 J2Cache ?

更多项目收集中,如果你的项目用了,请告诉我

TODO

  1. 应用重启,从 Redis 获取数据后,一级缓存的有效期大于预设值
  2. 多节点强一致性?
  3. 欢迎大家给 J2Cache 提建议
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: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and 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 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 2013 红薯 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.

简介

Java 两级缓存框架,可以让应用支持两级缓存框架 ehcache(Caffeine) + redis 。避免完全使用独立缓存系统所带来的网络IO开销问题 展开 收起
Java 等 2 种语言
Apache-2.0
取消

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/ld/J2Cache.git
git@gitee.com:ld/J2Cache.git
ld
J2Cache
J2Cache
master

搜索帮助

14c37bed 8189591 565d56ea 8189591