java缓存模块,ehcache/guava cache/自定义spring的CacheManager/自定义缓存

news2024/9/24 23:24:48

如ehcache,guava cache,redis

也有将ehcache,guava cache分级为单机缓存

将redis分为分布式缓存

ehcache官网:https://www.ehcache.org/

这里主要说下ehcache和guava cache

单独使用ehcache(当然真正企业开发并不会单独使用ehcache,而是会和Spring或者SpringBoot集成使用)

ehcache依赖:

<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
  <version>2.10.6</version>
</dependency>

注意ehcache的原生API在实际开发中一般不使用,而是和Spring或者SpringBoot集成使用,但是原理还是ehcache,只不过在Spring和SpringBoot中对它进行了包装,学习ehcache原生API可以帮助理解

这里是建了个Maven工程,引入的依赖,包含了Spring,SpringBoot

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!--springboot web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--spring aop + aspectj starter-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!--引入spring的 cache 支持 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <!--缓存实现-->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--jsr107缓存规范-->
        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!--lombok,springboot中已定义版本-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>29.0-jre</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

        <!--redisson的一部分代码是实现了jsr107的,分布式锁-->
        <!--    <dependency>-->
        <!--      <groupId>org.redisson</groupId>-->
        <!--      <artifactId>redisson</artifactId>-->
        <!--      <version>3.16.2</version>-->
        <!--    </dependency>-->


        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

使用原生ehcache的API

ehcache.xml配置

<?xml version="1.0" encoding="utf-8"?>
<ehcache
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="https://www.ehcache.org/ehcache.xsd">

  <!--
    path:默认写到磁盘的路径:C:\Users\user\AppData\Local\Temp\  -->
  <diskStore path="java.io.tmpdir"/>

  <!--
    对应类:net.sf.ehcache.config.CacheConfiguration
    maxEntriesLocalHeap:内存中最多放多少个元素
    memoryStoreEvictionPolicy:驱逐策略,net.sf.ehcache.store.MemoryStoreEvictionPolicy.fromString
    eternal:true:不过期
    timeToIdleSeconds:eternal=false时有效,可以闲置多长时间,单位s
    timeToLiveSeconds:eternal=false时有效,从创建开始计算可以存活多长时间,单位s
    maxElementsOnDisk:localTempSwap时有效,表示最多可以往磁盘写多少个
    diskExpiryThreadIntervalSeconds:localTempSwap时有效,检查磁盘元素是否失效的时间间隔
    persistence:当cache中的元素个数=maxEntriesLocalHeap时,
          localTempSwap:写到磁盘,其他值: net.sf.ehcache.config.PersistenceConfiguration.Strategy
    statistics:开启统计
  -->
  <cache
      name="user_cache"
      maxEntriesLocalHeap="1000"
      eternal="false"
      timeToIdleSeconds="600"
      timeToLiveSeconds="600"
      maxElementsOnDisk="10000000"
      diskExpiryThreadIntervalSeconds="120"
      memoryStoreEvictionPolicy="LRU"
      statistics="true"
  >
    <persistence strategy="localTempSwap"/>
  </cache>
</ehcache>

Test

相对路径:

String absPath="./src/main/resources/ehcache.xml";
 @Test
    public void test2(){
        System.out.println(System.getProperty("java.io.tmpdir"));
    }

    /**
     * 单独使用ehcache的api进行编程
     */
    @Test
    public void test1(){
        String absPath = "D:\\cache-demo\\src\\main\\resources\\ehcache.xml";
        /*
         用来管理多个Cache,user_cache、item_cache、store_cache...
         */
        CacheManager cacheManager = CacheManager.create(absPath);
        /*
         获取到CacheManager管理的所有的cache
         */
        String[] cacheNames = cacheManager.getCacheNames();
        System.out.println("CacheManager管理的所有的cache的名字"+ Arrays.toString(cacheNames));
        /*
         获取cache的名字(我们指定的)获取具体的cache
         */
        Cache userCache = cacheManager.getCache("user_cache");
        /*
         往userCache放入一个user
         */
        User user = new User();
        user.setId(1001L);
        user.setName("劈里啪啦");
        Element element = new Element(user.getId(),user);
        userCache.put(element);
        /*
        通过key取出缓存的对象
         */
        Element resultEle = userCache.get(1001L);
        System.out.println("获取到的resultEle:" +resultEle);
        System.out.println("获取Element的value:" + resultEle.getObjectValue());
    }

 关于jsr107缓存规范

依赖

<!-- JCACHE-->
<dependency>
  <groupId>javax.cache</groupId>
  <artifactId>cache-api</artifactId>
  <version>1.1.1</version>
</dependency>

  • jcp介绍: The Java Community Process(SM) Program - JSRs: Java Specification Requests - detail JSR# 107

  • 项目地址: GitHub - jsr107/jsr107spec: JSR107 Cache Specification

api结构

如何理解上面这张图:就是说一个应用程序下面,有很多个CahingProvider,每个CachingProvider里又包含很多CacheManager,每个CacheManager里有包含很多Cache 

对于jsr107缓存规范只做了解,过于复杂

下面是Spring的缓存抽象,设计就相对简单了

 就是说一个应用里面有一个CacheManager,管理着多个Cache

ehcache与Spring集成以及编程式操作缓存

Spring依赖一开始就已经引入了

Spring集成ehCache两种方式:

1.编程式使用

2.注解方式使用

注意在Spring集成ehcache的这张图

新建一个测试类

1.编程式使用

spring-ehcache.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/cache
           http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
    <!--相当于CacheManager cacheManager = CacheManager.create(absPath);-->
    <bean
        id="ehCacheManager"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <!--配置ehcache.xml的路径-->
      <property name="configLocation" value="classpath:ehcache.xml"/>
    </bean>
    <!--Spring中对原生的CacheManager进行包装,
    org.springframework.cache.CacheManager有多个实现
    -->
    <bean
        id="ehCacheCacheManager"
        class="org.springframework.cache.ehcache.EhCacheCacheManager">
      <property name="cacheManager" ref="ehCacheManager"/>
      <!--事务回滚缓存也回滚-->
      <property name="transactionAware" value="true"/>
    </bean>

    <!--和上面是同级的,指定用哪个实现类-->
<!--    <bean-->
<!--        id="concurrentMapCacheManager"-->
<!--        class="org.springframework.cache.concurrent.ConcurrentMapCacheManager">-->
<!--      <property name="cacheNames">-->
<!--        <list>-->
<!--          <value>item_cache</value>-->
<!--          <value>store_cache</value>-->
<!--        </list>-->
<!--      </property>-->
<!--    </bean>-->

  <!--跟org.springframework.cache.annotation.EnableCaching一样-->
  <cache:annotation-driven proxy-target-class="true"
                           cache-manager="ehCacheCacheManager"/>

</beans>

现在可以开始玩了

 

 

 打印了,但是控制台最后也报错了,说没有实现序列化

 原因是

 解决方式:1个改成不写入磁盘

2,那就是实现序列化

2.注解方式使用  使用@Cacheable

比如顶一个接口

 

 

下面就是实际开发中会用到的

SpringBoot集成ehcache

依赖一开始就已引入

直接测试

写个启动类,且加上@EnableCaching注解

 在yml里的配置

 现在用的是SpringBoot,将UserServiceImpl上加上@Service注解

 SpringBoot中编程式使用ehcashe和Spring是一样的

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/97920.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

什么是建筑中的“光储直柔”

建筑“光储直柔”与零碳电力如影随形&#xff08;2021&#xff09; 《2030 年前碳达峰行动方案》&#xff08;国发〔2021〕23 号&#xff09;中明确提出&#xff1a;提高建筑终端电气化水平&#xff0c;建设集光伏发电、储能、直流配电、柔性用电于一体的“光储直柔”建筑。到 …

广告、推荐模型加速策略整理

当我们尝试那些开箱即用的GPU服务时&#xff0c;很快意识到在经济高效地利用GPU运行推荐模型服务之前需要对其优化。我们首先使用分析工具来分析在模型推理过程中发生了什么&#xff0c;在仔细观察分析结果时&#xff0c;我们注意到时间线上有大量的小CUDA Kernel在执行。 这是…

[附源码]Python计算机毕业设计Django汽配管理系统

项目运行 环境配置&#xff1a; Pychram社区版 python3.7.7 Mysql5.7 HBuilderXlist pipNavicat11Djangonodejs。 项目技术&#xff1a; django python Vue 等等组成&#xff0c;B/S模式 pychram管理等等。 环境需要 1.运行环境&#xff1a;最好是python3.7.7&#xff0c;我…

linux内核内存管理-brk系统调用

【推荐阅读】 深入linux内核架构--进程&线程 浅谈linux 内核网络 sk_buff 之克隆与复制 浅析linux内核网络协议栈--linux bridge 尽管可见度不高&#xff0c;brk也许是最常使用的系统调用了&#xff0c;用户进程通过它向内核申请空间。人们常常并不意识到在调用brk&…

Python Flask构建微信小程序订餐系统 (三)

&#x1f525; 管理员登录和列表界面 &#x1f525; 账号相关登录界面 1、新建 User 对象文件 2、新建login (登录的方法)、edit (编辑的方法)、reset-pwd(重置密码的方法)方法 3、新建对应的视图层 账户管理相关界面 1、新建 Account 对象文件 2、新建index(账户列表)、set(新…

基于 Spring Cloud 的微服务脚手架

基于 Spring Cloud 的微服务脚手架 作者&#xff1a; Grey 原文地址&#xff1a; 博客园&#xff1a;基于 Spring Cloud 的微服务脚手架 CSDN&#xff1a;基于 Spring Cloud 的微服务脚手架 本文主要介绍了基于 Spring Cloud Finchley 和 Spring Boot 2.0.x 版本的微服务脚…

2006-2019年280个地级市绿色全要素生产率含原始数据和测算结果

2006-2019年280个地级市绿色全要素生产率含原始数据和测算结果 1、时间&#xff1a;2006-2019年 2、来源&#xff1a;原始数据来自各省NJ 城市NJ、各市NJ、各市社会统计GB 3、范围&#xff1a;包括280个地级市 4、指标包括&#xff1a; 投入&#xff1a;地级市市辖区从业人…

Spring Boot热部署配置

⭐️前言⭐️ 在我们进行Spring Boot项目的编写过程中&#xff0c;会有局部的代码&#xff0c;发生一些变动&#xff0c;这时候&#xff0c;我们只有将项目重启&#xff0c;发生变动的代码才能够生效&#xff0c;为了解决这个问题&#xff0c;我们可以设置Spring Boot热部署&a…

ClassLoader 隔离性的基石是namespace,证明给你看

一、背景 朋友&#xff1a;在我知识体系中ClassLoader的双亲委派机制是流畅丝滑的&#xff0c;可是看到通过委派执行类加载来保障这种分治能力&#xff0c;进而达到了类资源的隔离性突然就感觉有点陌生和排斥呢&#xff1f; 我&#xff1a;类的命名空间有了解嘛&#xff1f; …

Tableau可视化设计案例-01Tableau简介,条形图与直方图

文章目录Tableau可视化设计案例Tableau简介&#xff0c;条形图与直方图Tableau界面介绍Tableau绘制条形图2.1条形图1 各地区酒店数量2.2条形图2&#xff1a;各地区酒店均价2.3堆积图&#xff1a;价格等级堆积图Tableau绘制直方图3.1直方图概念与用途3.2创建评分直方图Tableau饼…

python中的split函数

返回数据类型为list # split以空格切片,返回数据类型为list a"I LOVE Python" print(a.split(" ")) print(type(a.split(" ")))运行结果如下&#xff1a; 可指定分隔符 # split以.切片,返回数据类型为list b"www.baidu.com" print…

Python工程师培训要多久?

Python作为目前备受初学者青睐的编程语言&#xff0c;学习的难度与其他语言相比&#xff0c;还是比较容易入门的。当然&#xff0c;一些零基础的初学者想要一两个月就能速成Python&#xff0c;还是不太可能的。尤其是想在学完之后应聘相关岗位&#xff0c;就算是最快的学习方式…

Dubbo 4 Dubbo 高级特性 4.2 Dubbo 常用高级配置 4.2.4 重试 4.2.5 多版本

Dubbo 【黑马程序员Dubbo快速入门&#xff0c;Java分布式框架dubbo教程】 4 Dubbo 高级特性 文章目录Dubbo4 Dubbo 高级特性4.2 Dubbo 常用高级配置4.2.4 重试4.2.5 多版本4.2 Dubbo 常用高级配置 4.2.4 重试 之前我们已经完成 了超时的配置 而且知道 了如果服务提供方 和消…

Linux 中存在太多的垃圾文件?

不知道大家是否也跟我一样&#xff0c;是一只要把的自己电脑文件安排的条理有序&#xff0c;把没用的文件会及时删掉的程序猿呢&#xff1f;如果是的话&#xff0c;那么我们可以愉快地探讨下文章的内容。如果不是的话&#xff0c;你也可以留下来凑凑热闹嘛(>- 下面要介绍的是…

基于java+springmvc+mybatis+vue+mysql的邮票鉴赏系统及实现

项目介绍 随着邮票行业的发展&#xff0c;邮票市场已经有了越来越多的爱好者加入。收藏邮票&#xff0c;也就成了邮票收藏爱好者一个有爱又恨的话题。没错&#xff0c;大量的邮票收藏确实是对知识面的增广和一种成就感的满足。但是面对越来越多的邮票。五花八门各种各样的邮票…

十四、CANdelaStudio入门-DID池

本专栏将由浅入深的展开诊断实际开发与测试的数据库编辑,包含大量实际开发过程中的步骤、使用技巧与少量对Autosar标准的解读。希望能对大家有所帮助,与大家共同成长,早日成为一名车载诊断、通信全栈工程师。 本文介绍CANdelaStudio的DID池,欢迎各位朋友订阅、评论,可以提…

【C++进阶】C++11新特性上篇(万字详解)

&#x1f387;C学习历程&#xff1a;入门 博客主页&#xff1a;一起去看日落吗持续分享博主的C学习历程博主的能力有限&#xff0c;出现错误希望大家不吝赐教分享给大家一句我很喜欢的话&#xff1a; 也许你现在做的事情&#xff0c;暂时看不到成果&#xff0c;但不要忘记&…

Dubbo 4 Dubbo 高级特性 4.2 Dubbo 常用高级配置 4.2.6 负载均衡

Dubbo 【黑马程序员Dubbo快速入门&#xff0c;Java分布式框架dubbo教程】 4 Dubbo 高级特性 文章目录Dubbo4 Dubbo 高级特性4.2 Dubbo 常用高级配置4.2.6 负载均衡4.2 Dubbo 常用高级配置 4.2.6 负载均衡 【举个栗子】 现在 同一个服务 提供者&#xff0c;我们把它 部署在了…

Dijkstra迪杰斯特拉算法

1.场景 用于计算一个节点到其他节点的最短路径&#xff0c;特点是由其实点位中心向外层扩展&#xff08;BFS思想&#xff09;&#xff0c;直至扩展到终点为止 2.认识 https://blog.csdn.net/weixin_57128596/article/details/126982769?ops_request_misc%257B%2522request%…

自动生成changelog

本文主要记录我如何在React项目中优雅的使用TypeScript&#xff0c;来提高开发效率及项目的健壮性。 项目目录及ts文件划分 由于我在实际项目中大部分是使用umi来进行开发项目&#xff0c;所以使用umi生成的目录来做案例。 . ├── README.md ├── global.d.ts ├── mo…