Spring Boot - EnCaching

Spring Boot - EnCaching 首页 / Spring Boot入门教程 / Spring Boot - EnCaching

EhCache是​​一种基于Java的开源缓存,用于提高性能。 Ehcache的当前版本为3。它提供JSR-107缓存管理器的实现。无涯教程可以直接使用它。

    EhCache示例

    在下面的示例中,无涯教程将在应用程序中配置EhCache。

    步骤1  -  打开Spring Initializr https://start.spring.io/。

    步骤2  -  选择Spring Boot版本2.3.0 M2。

    步骤3  -  Group处填写 com.learnfk。

    步骤4  -  Artifact处填写 spring-boot-ehcache-example

    步骤5  -  添加 Spring Web 依赖项。

    步骤6  -  单击 Generate (生成)按钮。当单击Generate按钮时,它将与应用程序相关的所有规范包装到 Jar 文件中,并将其下载到本地系统。

    步骤7  -   提取(Extract) jar文件。

    步骤8  -   复制文件夹并将其粘贴到STS工作区中。

    步骤9  -  导入(Import)该项目。

    File -> Import -> Existing Maven Projects -> Next -> Browse -> Select the folder spring-boot-ehcache-example -> Select Folder -> Finish

    导入项目需要时间。

    步骤10 -  Maven 存储库 https://mvnrepository.com/ 并将其粘贴到 pom.xml 文件中。

    • spring-boot-starter-cache
    • ehcache 3
    • cache API。

    Note: 不要使用包net.sf.ehcache的ehcache。

    pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.0.M2</version>
    <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.learnfk</groupId>
    <artifactId>spring-boot-ehcache-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-ehcache-example</name>
    <description>Demo project for Spring Boot</description>
    <properties>
    <java.version>1.8</java.version>
    </properties>
    <dependencies>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    </dependency>
    <dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
    <exclusion>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    </exclusion>
    </exclusions>
    </dependency>
    </dependencies>
    <build>
    <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
    </plugins>
    </build>
    <repositories>
    <repository>
    <id>spring-milestones</id>
    <name>Spring Milestones</name>
    <url>https://repo.spring.io/milestone</url>
    </repository>
    </repositories>
    <pluginRepositories>
    <pluginRepository>
    <id>spring-milestones</id>
    <name>Spring Milestones</name>
    <url>https://repo.spring.io/milestone</url>
    </pluginRepository>
    </pluginRepositories>
    </project>

    现在,无涯教程需要配置 ehcache.xml 文件。它告诉框架在哪里找到文件。

    步骤11  -  打开application.properties文件,并使用以下属性配置EhCache。

    application.properties

    #configuring ehcache.xml
    spring.cache.jcache.config=classpath:ehcache.xml

    步骤12  -  打开 SpringBootEhcacheExampleApplication.java 文件,并使用注释 @EnableCaching 启用缓存。

    SpringBootEhcacheExampleApplication.java

    package com.learnfk;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    @SpringBootApplication
    @EnableCaching
    public class SpringBootEhcacheExampleApplication 
    {
      public static void main(String[] args) 
      {
        SpringApplication.run(SpringBootEhcacheExampleApplication.class, args);
      }
    }

    Note: 如果不想在主应用程序文件中使用注解@EnableCaching,则可以创建一个单独的CacheConfig类,并用注解对该调用进行注解。

    package com.learnfk;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.context.annotation.Configuration;
    @Configuration
    @EnableCaching
    public class CacheConfig 
    {
    }

    步骤13 - 创建模型类。已经在包 com.learnfk 中创建了名称为 Student的模型类。 在模型类中,执行以下操作:

    • 创建id,name,gender和city变量
    • 使用字段生成构造函数。右键单击 file -> Source -> Generate Constructor using Fields -> Select All -> Generate
    • 生成Getters和Setters。右键单击 file -> Source -> Generate Getters and Setters -> Select All -> Generate
    • 生成一个toString()
    • 右键单击  file -> Source -> Generate toString() -> Generate

    完成上述所有步骤后,模型类如下所示。

    Student.java

    package com.learnfk;
    public class Student 
    {
      private int id;
      private String name;
      private String gender;
      private String city;
      public Student(int id, String name, String gender, String city) 
      {
        super();
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.city = city;
      }
      public int getId() 
      {
        return id;
      }
      public void setId(int id) 
      {
        this.id = id;
      }
      public String getName() 
      {
        return name;
      }
      public void setName(String name) 
      {
        this.name = name;
      }
      public String getGender() 
      {
        return gender;
      }
      public void setGender(String gender) 
      {
        this.gender = gender;
      }
      public String getCity() 
      {
        return city;
      }
      public void setCity(String city) 
      {
        this.city = city;
      }
      @Override
      public String toString() 
      {
        return "Student [id=" + id + ", name=" + name + ", gender=" + gender + ", city=" + city + "]";
      }
    }  

    步骤14  -  创建一个管理学生的Service类。已经创建了名称为 StudentManager的服务类。 在本课程中,完成了以下操作:

    • 使用注释 @Service注释类。
    • 创建 HashMap 的实例。
    • 在静态块中,已在映射中添加了学生数据。
    • 通过使用注释 @Cacheable ,定义了缓存的名称所有数据都将保存在此缓存中。已经在注释的 key 属性中定义了 id 。缓存根据 id 来搜索学生。
    • 创建了一种方法 getStudentById(),该方法将id解析为参数。它返回学生的 id

    StudentManager.java

    StudentManager.java
    package com.learnfk;
    import java.util.HashMap;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    @Service
    public class StudentManager 
    {
      static HashMap<Integer, Student> student = new HashMap<>();
      static 
      {
        student.put(1, new Student(100, "Alex", "Male", "Berlin"));
        student.put(2, new Student(101, "Tony", "Male", "Maxico"));
        student.put(3, new Student(102, "Andrew", "Male", "Chicago"));
        student.put(4, new Student(103, "Alexa", "Female", "Brussels"));
        student.put(5, new Student(104, "Maria", "Female", "Houston"));
      }
      @Cacheable(cacheNames="demoCache", key="#id")
      public Student getStudentById(Integer id) 
      {
        System.out.println("Fetching student data from cache");
        return student.get(id);
      }
    }

    现在,需要创建 ehcache.xml 文件。它包含与高速缓存有关的信息,例如高速缓存的名称,内存中的元素数量,高速缓存中的实时数据生存时间。

    步骤15  -   src/main/resources 文件夹中创建一个名为 ehcache.xml 的缓存配置文件。

    ehcache.xml

    <config
    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns='http://www.ehcache.org/v3'
    xmlns:jsr107='http://www.ehcache.org/v3/jsr107'>
    <ehcache>
    <diskStore path="java.io.tmpdir" />
    <defaultCache maxElementsInMemory="2000" 
    			eternal="true"
    			overflowToDisk="false" 
    			timeToLiveSeconds="1200" />
    	<cache name="demoCache" 
    			maxElementsInMemory="2000"
    			eternal="false" 
    			overflowToDisk="false" 
    			timeToLiveSeconds="10000" />
    </ehcache>
    </config>

    现在,已经创建了所有必需的文件。创建所有文件后,项目目录如下所示:

    Spring Boot EhCaching

    让无涯教程运行该应用程序。

    步骤16  -   打开SpringBootEhcacheExampleApplication.java文件,并将其作为Java应用程序运行。

    它显示以下输出:

    Getting Students from Cache
    [id=100, name=Alex, gender=Male, city=Berlin]
    [id=101, name=Tony, gender=Male, city=Mexico]
    [id=102, name=Andrew, gender=Male, city=Chicago]
    [id=103, name=Alexa, gender=Female, city=Brussels]
    [id=104, name=Maria, gender=Female, city=Houston]

    祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

    技术教程推荐

    左耳听风 -〔陈皓〕

    微服务架构核心20讲 -〔杨波〕

    微服务架构实战160讲 -〔杨波〕

    白话法律42讲 -〔周甲徳〕

    罗剑锋的C++实战笔记 -〔罗剑锋〕

    Redis核心技术与实战 -〔蒋德钧〕

    Spark核心原理与实战 -〔王磊〕

    程序员的测试课 -〔郑晔〕

    AI大模型之美 -〔徐文浩〕

    好记忆不如烂笔头。留下您的足迹吧 :)