springboot 整合EHcache 实现分页缓存

2023-11-20

一 简要概述

@Cacheable 对当前的对象做缓存处理

@Cacheable 作用:把方法的返回值添加到 Ehcache 中做缓存

@Cacheable (value=“xxx”,key="xxxx")

Value 属性:指定一个 Ehcache 配置文件中的缓存策略,如果没有给定 value,那么则表示使用默认的缓存策略

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

二 案例

2.1 工程结构

2.2 pom文件

    <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 的启动器 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- springBoot 的启动器 -->
    <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.1.10</version>
    </dependency>
    <!-- Spring Boot 缓存支持启动器 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <!-- Ehcache 坐标 -->
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
    </dependency>

2.3 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.4 model

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;
    }

    @Override
    public String toString() {
        return "Users [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
    }
}

2.5 service

接口层:

package com.ljf.spring.boot.demo.service;

import com.ljf.spring.boot.demo.model.Users;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;

public interface UserService {
    List<Users> findUserAll();
    public Page<Users> findUserByPage(Pageable pageable );
}

实现层:

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

   // @Cacheable(value="users",key="#pageable") //默认key的值为pageable
   // @Cacheable(value="users",key="#pageable.pageSize") //指定key的值为#pageable.pageSize
    public Page<Users> findUserByPage(Pageable pageable ){
        return this.userRepository.findAll(pageable);
    }

}

2.6 配置文件

1.application配置文件

#spring的配置mysql
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test_db?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
#ali
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.cache.ehcache.cofnig=ehcache.xml

2.ehcache缓存文件

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <diskStore path="java.io.tmpdir"/>

  <!--defaultCache:echcache的默认缓存策略  -->
    <defaultCache
            maxElementsInMemory="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.7 启动类

package com.ljf.spring.boot.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
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!" );

    }
}

2.8 测试类

    @Test
    public void queryByPage(){
        Pageable pageable= PageRequest.of(0, 10);
        Page<Users> list=us.findUserByPage(pageable);
        System.out.println("第1次:"+list.getContent().get(0).getAddress());
        Page<Users> list2=us.findUserByPage(pageable);
        System.out.println("第2次:"+list2.getContent().get(0).getAddress());
         pageable= PageRequest.of(0, 5);
        Page<Users> list3=us.findUserByPage(pageable);
        System.out.println("第3次:"+list3.getContent().get(0).getAddress());
    }

不加缓存,查询执行了3次查询数据库

2.9 添加缓存

在分页的方法上假如缓存,已分页的pageable作为key

通过执行结果看到:第一次执行查询数据库,第二次查询内存,当分页pageable= PageRequest.of(0, 10);改为pageable= PageRequest.of(0, 5);,再次执行时,重新查询数据库

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springboot 整合EHcache 实现分页缓存 的相关文章

随机推荐

  • Vue long精度丢失问题

    原因 vue前端对long类型的精度无法接收 javascript 的 Number 类型最大长度是17位 mysql 使用bigint 类型长度是20位 前端解决方法 在全局的网络请求 用了一个处理数据的插件 来转换 后端解决的方法 Co
  • 网络安全不可忽视!企业如何做好网络安全。

    随着互联网的高速发展 其面临的安全隐患也暴露无疑 比如网络攻击 黑客入侵等 都会严重影响到网络业务的运行 为此很多企业都绞尽脑汁寻找抵御各类网络安全隐患 国家也出台了相关的等保方案让企业能够免于后顾之忧 下面我们来说说目前网络安全的具体内容
  • android音视频!BAT大厂面试基础题集合,不吃透都对不起自己

    前言 现在已经进入招聘季节 本篇文章旨在分享知名互联网企业面试官面试方法和心得 希望通过本文的阅读能给程序员带来不一样的面试体验和感受 放松面试心态 积极备战 找到正确的学习路线 一 架构师专题 想要掌握复杂的技术 必须要理解其原理和架构
  • ROS学习笔记(二)文件系统

    ROS学习笔记 二 文件系统 开篇 ROS的文件系统结构 要学会建立一个ROS工程 首先要认识一个ROS工程 了解它们的组织架构 从根本上熟悉ROS项目的组织形式 了解各个文件的功能和作用 才能正确的进行开发和编程 本章的主要内容有 介绍c
  • 就现在!为元宇宙和Web3对互联网的改造做准备!

    欢迎来到Hubbleverse 关注我们 关注宇宙新鲜事 预计阅读时长 8分钟 本文仅代表作者个人观点 不代表平台意见 不构成投资建议 如今 互联网是各种不同的网站 应用程序和平台的集合 由于彼此分离 它们缺乏互操作性和数据可移植性 因此
  • ant design vue中menu组件递归渲染报错解决

    ant design vue中menu组件递归渲染报错 开始递归组件后打开页面后报错如下 解决如下 使 单 件 式递归 成菜单 Before v2 0 因组件内部会动态更改a sub menu的属性 如果拆分单文件 无法将属性挂载到a su
  • BI的需求调研的方法分类

    今天看到一篇文章 里面提到需求调研的几种思路 觉得分类有些道理 结合项目写一下 这种方法论在指导实践和体现专业两个方面都很实用 1 现有报表 这个是最常用的 使用这种方法注意区别报表目的 紧急度 和数据是否适合在BI实现 细节度 为什么以前
  • Oracle统计多张表的Count数的和

    需求描述 Table1 job1 job1 id name status other column 1 file1 process 2 file2 failed 3 file3 success Table2 job2 job2 id nam
  • 03:MYSQL----DQL,聚合函数

    目录 1 介绍 2 语法 3 聚合函数 4 DOL 语句练习 5 SQL执行顺序 1 介绍 数据查询语言 用来查询数据库中表的记录 2 语法 select 字段列表 from 表名列表 where 条件列表 group by 分组字段列表
  • 手写 git hooks 脚本

    我们的 Git 仓库中包含了编译后的代码 所以每次修改了源码 都需要运行一下编译命令 然后把源码和编译后的代码一起提交到 Git 仓库 这个流程没什么问题 但是 人脑不是电脑 总会有疏忽的时候 经常会出现这样一种情况 修改了源码 却忘记了运
  • sql判断字段是否为null,是否为空串

    问题现象 今天在项目中思考了一个问题 如何在sql中判断一个字段是否为 null值 是否为 空串 呢 问题分析 需要注意的是 null值 和 空串 并不是同一个概念 null值 就是这个字段没有赋值 也就是java中常说的 null 而 空
  • 权重实现随机抽奖

    一般抽奖是怎么实现的 在实习期间学会了一种通用的写法 在这里记录一下 最近在学Golang语法基础 这里就用Golang来写 package main import fmt time math rand func main r rand N
  • 模态对话框与非模态对话的几种销毁方法与区别

    前几天发现自己的程序中使用非模态对话框 Debug版本有警告提示如下 Warning calling DestroyWindow in CWnd CWnd OnDestroy or PostNcDestroy in derived clas
  • 关于高并发与多线程中的线程池

    关于高并发与多线程中的线程池 定义 线程是稀缺资源 它的创建与销毁是一个相对偏重且耗资源的操作 而Java线程依赖于内核线程 创建线程需要进行操作系统状态切换 为避免资源过度消耗需要设法重用线程执行多个任务 线程池就是一个线程缓存 负责对线
  • Qt webengine 显示web页面、前后端通信以及下载详解

    概述 官方文档 https doc qt io archives qt 5 11 qtwebengine overview html 翻译文档 Qt5 9 WebEngine 概述 一花一世界 一叶一乾坤 博客园 从Qt5 5开始 Qt W
  • libuv 原理_[Nodejs原理] 核心库Libuv入门(Hello World篇)

    Libuv是什么 1 简介Libuv是一个高性能的 事件驱动的异步I O库 它本身是由C语言编写的 具有很高的可移植性 libuv封装了不同平台底层对于异步IO模型的实现 所以它还本身具备着Windows Linux都可使用的跨平台能力 L
  • 数据密集型应用系统设计(2)

    文章目录 数据模型与查询语言 NoSQL 数据库历史 关系数据库与文档数据库现状 数据查询语言 图状数据模型 小结 数据模型与查询语言 大多数应用程序是通过一层层叠加数据模型来构建的 例如 应用程序开发人员观测现实世界 通过对象或者数据结构
  • Vue 和 jQuery 两者之间的区别是什么?

    1 jQuery 介绍 jQuery 曾经也是现在依然最流行的 web 前端 js 库 可是现在无论是国内还是国外他的使 用率正在渐渐被其他的 js 库所代替 随着浏览器厂商对 HTML5 规范统一遵循以及 ECMA6 在浏 览器端的实现
  • NGINX配置PHP网站

    NGINX配置PHP网站 NGINX配置PHP网站 源码安装NGINX 安装PHP 修改PHP参数 重启PHP 修改nginx配置文件 重启NGINX 测试 解决报错问题 NGINX配置PHP网站 源码安装NGINX 脚本一键安装 安装路径
  • springboot 整合EHcache 实现分页缓存

    一 简要概述 Cacheable 对当前的对象做缓存处理 Cacheable 作用 把方法的返回值添加到 Ehcache 中做缓存 Cacheable value xxx key xxxx Value 属性 指定一个 Ehcache 配置文