springboot 整合EHcache 实现缓存技术

2024-05-29 08:48

本文主要是介绍springboot 整合EHcache 实现缓存技术,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一 ehcache的概述

1.@Cacheable注解的作用

@Cacheable 对当前的对象做缓存处理
@Cacheable
public List<Users> findUserAll() {return this.userRepository.findAll();
}@Cacheable 作用:把方法的返回值添加到 Ehcache 中做缓存 Value 属性:指定一个 Ehcache 配置文件中的缓存策略,如果没有给定 value,那么则表示使用默认的缓存策略
@Cacheable(value = "users")
public List<Users> findUserAll() {return this.userRepository.findAll();
}

key的作用:给存储的值起个名称,在查询时如果有名称相同时,则从已知的名称中取值。 否则从数据库中查询数据。

配置文件设置缓存策略:

注意事项:缓存的对象必须实现序列化

二 操作案例

2.1.新建项目配置pom文件

加配置依赖:

   <!-- Spring Boot缓存支持启动器 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <!-- Ehcache坐标 -->
    <dependency>
      <groupId>org.ehcache</groupId>
      <artifactId>ehcache</artifactId>
      <version>3.1.2</version>
    </dependency>

    <dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13</version><scope>test</scope></dependency><!-- springBoot的启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- springBoot的thymeleaf启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><!-- springBoot的jpa启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!-- 测试工具的启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><!-- mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- druid连接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.9</version></dependency><!-- Spring Boot缓存支持启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency><!-- Ehcache坐标 --><dependency><groupId>org.ehcache</groupId><artifactId>ehcache</artifactId><version>3.1.2</version></dependency>

2.2 dao层

package com.ljf.spring.boot.demo.dao;import com.ljf.spring.boot.demo.model.Users;
import org.springframework.data.jpa.repository.JpaRepository;/*** 参数一 T :当前需要映射的实体* 参数二 ID :当前映射的实体中的OID的类型**/
public interface UserRepository extends JpaRepository<Users,Integer> {}

2.3.model层

 注意users要实现序列化

package com.ljf.spring.boot.demo.model;import javax.persistence.*;
import java.io.Serializable;/*** @ClassName: Users* @Description: TODO* @Author: liujianfu* @Date: 2020/09/02 08:50:18 * @Version: V1.0**/@Entity@Table(name="tb_users_tb")public class Users implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "id")private Integer id;@Column(name = "name")private String name;@Column(name = "age")private Integer age;@Column(name = "address")private String address;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "Users [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";}
}

 2.4.service层

public interface UserService {List<Users> findUserAll();
}package com.ljf.spring.boot.demo.service.impl;import com.ljf.spring.boot.demo.dao.UserRepository;
import com.ljf.spring.boot.demo.model.Users;
import com.ljf.spring.boot.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;import java.util.List;/*** @ClassName: UserServiceImpl* @Description: TODO* @Author: liujianfu* @Date: 2020/09/02 08:57:11 * @Version: V1.0**/
@Service
public class UserServiceImpl  implements UserService {@Autowiredprivate UserRepository userRepository;@Override//@Cacheable 对当前的对象做缓存处理//@Cacheable(value = "users")public List<Users> findUserAll() {return this.userRepository.findAll();}}

2.5.配置文件

2.5.1 application配置文件

在配置文件中引入缓存的配置文件:
spring.cache.ehcache.cofnig=ehcache.xml

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test_db
spring.datasource.username=root
spring.datasource.password=rootspring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=truespring.cache.ehcache.cofnig=ehcache.xml

2.5.2 ehcache.xml配置文件

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"><diskStore path="java.io.tmpdir"/><!--defaultCache:echcache的默认缓存策略  --><defaultCachemaxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"maxElementsOnDisk="10000000"diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU"><persistence strategy="localTempSwap"/></defaultCache><!-- 自定义缓存策略 --><cache name="users"maxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"maxElementsOnDisk="10000000"diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU"><persistence strategy="localTempSwap"/></cache>
</ehcache>

2.6 启动类和测试类

启动类上添加,开启缓存的注解@EnableCaching

package com.ljf.spring.boot.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;/*** Hello world!**/
@SpringBootApplication
@EnableCaching
public class StartApp
{public static void main( String[] args ){SpringApplication.run(StartApp.class, args);System.out.println( "Hello World!" );}
}
package com.ljf.spring.boot.demo;import static org.junit.Assert.assertTrue;import com.ljf.spring.boot.demo.model.Users;
import com.ljf.spring.boot.demo.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;/*** Unit test for simple App.*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={StartApp.class})   //springboot的启动类
public class AppTest 
{@Autowiredprivate UserService us;/*** Rigorous Test :-)*/@Testpublic void query(){List<Users> list=us.findUserAll();System.out.println("第一次:"+list.get(0).getAddress());List<Users> list2=us.findUserAll();System.out.println("第2次:"+list2.get(0).getAddress());}
}

 2.7.不加缓存执行

2.8.开启缓存执行

通过console打印的日志可以看到:只打印了一次数据库的日志,查询了一次数据库。

 

这篇关于springboot 整合EHcache 实现缓存技术的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1013193

相关文章

Java中的Cursor使用详解

《Java中的Cursor使用详解》本文介绍了Java中的Cursor接口及其在大数据集处理中的优势,包括逐行读取、分页处理、流控制、动态改变查询、并发控制和减少网络流量等,感兴趣的朋友一起看看吧... 最近看代码,有一段代码涉及到Cursor,感觉写法挺有意思的。注意是Cursor,而不是Consumer

解决java.lang.NullPointerException问题(空指针异常)

《解决java.lang.NullPointerException问题(空指针异常)》本文详细介绍了Java中的NullPointerException异常及其常见原因,包括对象引用为null、数组元... 目录Java.lang.NullPointerException(空指针异常)NullPointer

javaScript在表单提交时获取表单数据的示例代码

《javaScript在表单提交时获取表单数据的示例代码》本文介绍了五种在JavaScript中获取表单数据的方法:使用FormData对象、手动提取表单数据、使用querySelector获取单个字... 方法 1:使用 FormData 对象FormData 是一个方便的内置对象,用于获取表单中的键值

Vue ElementUI中Upload组件批量上传的实现代码

《VueElementUI中Upload组件批量上传的实现代码》ElementUI中Upload组件批量上传通过获取upload组件的DOM、文件、上传地址和数据,封装uploadFiles方法,使... ElementUI中Upload组件如何批量上传首先就是upload组件 <el-upl

前端知识点之Javascript选择输入框confirm用法

《前端知识点之Javascript选择输入框confirm用法》:本文主要介绍JavaScript中的confirm方法的基本用法、功能特点、注意事项及常见用途,文中通过代码介绍的非常详细,对大家... 目录1. 基本用法2. 功能特点①阻塞行为:confirm 对话框会阻塞脚本的执行,直到用户作出选择。②

Docker部署Jenkins持续集成(CI)工具的实现

《Docker部署Jenkins持续集成(CI)工具的实现》Jenkins是一个流行的开源自动化工具,广泛应用于持续集成(CI)和持续交付(CD)的环境中,本文介绍了使用Docker部署Jenkins... 目录前言一、准备工作二、设置变量和目录结构三、配置 docker 权限和网络四、启动 Jenkins

SpringBoot项目注入 traceId 追踪整个请求的日志链路(过程详解)

《SpringBoot项目注入traceId追踪整个请求的日志链路(过程详解)》本文介绍了如何在单体SpringBoot项目中通过手动实现过滤器或拦截器来注入traceId,以追踪整个请求的日志链... SpringBoot项目注入 traceId 来追踪整个请求的日志链路,有了 traceId, 我们在排

Java实战之利用POI生成Excel图表

《Java实战之利用POI生成Excel图表》ApachePOI是Java生态中处理Office文档的核心工具,这篇文章主要为大家详细介绍了如何在Excel中创建折线图,柱状图,饼图等常见图表,需要的... 目录一、环境配置与依赖管理二、数据源准备与工作表构建三、图表生成核心步骤1. 折线图(Line Ch

Python3脚本实现Excel与TXT的智能转换

《Python3脚本实现Excel与TXT的智能转换》在数据处理的日常工作中,我们经常需要将Excel中的结构化数据转换为其他格式,本文将使用Python3实现Excel与TXT的智能转换,需要的可以... 目录场景应用:为什么需要这种转换技术解析:代码实现详解核心代码展示改进点说明实战演练:从Excel到

如何使用CSS3实现波浪式图片墙

《如何使用CSS3实现波浪式图片墙》:本文主要介绍了如何使用CSS3的transform属性和动画技巧实现波浪式图片墙,通过设置图片的垂直偏移量,并使用动画使其周期性地改变位置,可以创建出动态且具有波浪效果的图片墙,同时,还强调了响应式设计的重要性,以确保图片墙在不同设备上都能良好显示,详细内容请阅读本文,希望能对你有所帮助...