Table of Contents
一、简介
二、引入 EhCache
1、引入依赖
2、配置文件
3、开启缓存
三、开始使用
1、@CacheConfig
2、@Cacheable
3、@CachePut
4、@CacheEvict
Home Java javaTutorial How to integrate Ehcache in SpringBoot to implement hotspot data caching

How to integrate Ehcache in SpringBoot to implement hotspot data caching

May 15, 2023 pm 09:10 PM
springboot ehcache

    一、简介

    EhCache 是一个纯 Java 的进程内缓存框架,具有快速、精干等特点,是 Hibernate 中默认CacheProvider。Ehcache 是一种广泛使用的开源 Java 分布式缓存。主要面向通用缓存,Java EE 和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个 gzip 缓存 servlet 过滤器,支持 REST 和 SOAP api 等特点。

    特性
    快速、简单
    多种缓存策略
    缓存数据有两级:内存和磁盘,因此无需担心容量问题
    缓存数据会在虚拟机重启的过程中写入磁盘
    可以通过RMI、可插入API等方式进行分布式缓存
    具有缓存和缓存管理器的侦听接口
    支持多缓存管理器实例,以及一个实例的多个缓存区域
    提供Hibernate的缓存实现
    与 Redis 相比
    EhCache 直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便。
    Redis 是通过 Socket 访问到缓存服务,效率比 EhCache 低,比数据库要快很多,处理集群和分布式缓存方便,有成熟的方案。如果是单个应用或者对缓存访问要求很高的应用,用 EhCache 。如果是大型系统,存在缓存共享、分布式部署、缓存内容很大的,建议用 Redis。
    EhCache 也有缓存共享方案,不过是通过 RMI 或者 Jgroup 多播方式进行广播缓存通知更新,缓存共享复杂,维护不方便;简单的共享可以,但是涉及到缓存恢复,大数据缓存,则不合适。

    二、引入 EhCache

    1、引入依赖

    在 pom.xml 文件中,引入 Ehcache 的依赖信息

    <!-- ehcache依赖 -->
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.10.6</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    Copy after login

    2、配置文件

    创建 EhCache 的配置文件:ehcache.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
     
        <!--
            磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
            path:指定在硬盘上存储对象的路径
            path可以配置的目录有:
            user.home(用户的家目录)
            user.dir(用户当前的工作目录)
            java.io.tmpdir(默认的临时目录)
            ehcache.disk.store.dir(ehcache的配置目录)
            绝对路径(如:d:\\ehcache)
            查看路径方法:String tmpDir = System.getProperty("java.io.tmpdir");
         -->
        <diskStore path="java.io.tmpdir" />
     
        <!--
            defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
            maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
            eternal:代表对象是否永不过期 (指定true则下面两项配置需为0无限期)
            timeToIdleSeconds:最大的发呆时间 /秒
            timeToLiveSeconds:最大的存活时间 /秒
            overflowToDisk:是否允许对象被写入到磁盘
            说明:下列配置自缓存建立起600秒(10分钟)有效 。
            在有效的600秒(10分钟)内,如果连续120秒(2分钟)未访问缓存,则缓存失效。
            就算有访问,也只会存活600秒。
         -->
        <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="600"
                      timeToLiveSeconds="600" overflowToDisk="true" />
     
        <!--
            maxElementsInMemory,内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况
                                1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中
                                2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素
            eternal,            缓存中对象是否永久有效
            timeToIdleSeconds,  缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除
            timeToLiveSeconds,  缓存数据的总的存活时间(单位:秒),仅当eternal=false时使用,从创建开始计时,失效结束
            maxElementsOnDisk,  磁盘缓存中最多可以存放的元素数量,0表示无穷大
            overflowToDisk,     内存不足时,是否启用磁盘缓存
            diskExpiryThreadIntervalSeconds,    磁盘缓存的清理线程运行间隔,默认是120秒
            memoryStoreEvictionPolicy,  内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存  共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)
        -->
        <cache name="user" 
        	maxElementsInMemory="10000" 
        	eternal="false" 
        	timeToIdleSeconds="120" 
        	timeToLiveSeconds="120" 
        	maxElementsOnDisk="10000000" 
        	overflowToDisk="true" 
        	memoryStoreEvictionPolicy="LRU" />
     
    </ehcache>
    Copy after login

    ,我们是可以配置多个来解决我们不同业务处所需要的缓存策略的

    默认情况下,EhCache 的配置文件名是固定的,ehcache.xml,如果需要更改文件名,需要在 application.yml 文件中指定配置文件位置,如:

    spring:
      cache:
        type: ehcache
        ehcache:
          config: classpath:/ehcache.xml
    Copy after login

    指定了 EhCache 的配置文件位置

    3、开启缓存

    开启缓存的方式,也和 Redis 中一样,在启动类上添加 @EnableCaching 注解即可:

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
     
    @SpringBootApplication
    @EnableCaching
    public class SbmApplication {
     
        public static void main(String[] args) {
            SpringApplication.run(SbmApplication.class, args);
        }
    }
    Copy after login

    三、开始使用

    1、@CacheConfig

    这个注解在类上使用,用来描述该类中所有方法使用的缓存名称,当然也可以不使用该注解,直接在具体的缓存注解上配置名称,示例代码如下:

    @Service
    @CacheConfig(cacheNames = "user")
    public class UserServiceImpl implements UserService {
     
    }
    Copy after login

    2、@Cacheable

    这个注解一般加在查询方法上,表示将一个方法的返回值缓存起来,默认情况下,缓存的 key 就是方法的参数,缓存的 value 就是方法的返回值。示例代码如下:

    @Override
    @Cacheable(value = "user", key = "#id")
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }
    Copy after login

    如果在类上没有加入 @CacheConfig,我们则需要使用 value 来指定缓存名称
    这里如果需要多个 key 时,需要使用 “:” 来连接,如:

    @Cacheable(value = "user", key = "#name+&#39;:&#39;+#phone")
    Copy after login

    3、@CachePut

    这个注解一般加在更新方法上,当数据库中的数据更新后,缓存中的数据也要跟着更新,使用该注解,可以将方法的返回值自动更新到已经存在的 key 上,示例代码如下:

    @Override
    @CachePut(value = "user", key = "#id")
    public User updateUserById(User user) {
        return userMapper.updateUserById(user);
    }
    Copy after login

    4、@CacheEvict

    这个注解一般加在删除方法上,当数据库中的数据删除后,相关的缓存数据也要自动清除,该注解在使用的时候也可以配置按照某种条件删除( condition 属性)或者或者配置清除所有缓存( allEntries 属性),示例代码如下:

    @Override
    @CacheEvict(value = "user", key = "#id")
    public void deleteUserById(Long id) {
        userMapper.deleteUserById(id);
    }
    Copy after login

    The above is the detailed content of How to integrate Ehcache in SpringBoot to implement hotspot data caching. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

    Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

    How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

    Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

    How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

    1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

    How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

    Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

    Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

    SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

    How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

    When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

    How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

    1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

    How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

    In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

    See all articles