springboot的ehcache的@CacheEvict清除缓存

2024-05-29 08:32

本文主要是介绍springboot的ehcache的@CacheEvict清除缓存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一 @CacheEvict的作用

1.1 总体概述

    @CacheEvict是用来标注在需要清除缓存元素的方法或类上的

当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。

@CacheEvict可以指定的属性有value、key、condition、allEntries和beforeInvocation。其中value、key和condition的语义与@Cacheable对应的属性类似。

即value表示清除操作是发生在哪些Cache上的(对应Cache的名称);key表示需要清除的是哪个key,如未指定则会使用默认策略生成的key;

condition表示清除操作发生的条件。下面我们来介绍一下新出现的两个属性allEntries和beforeInvocation。

1.2 allEntries属性

   allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allEntries为true时,清除缓存中的所有元素,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素,这比一个一个清除元素更有效率。

   @CacheEvict(value="users", allEntries=true)

   public void delete(Integer id) {

      System.out.println("delete user by id: " + id);

   }

1.3  beforeInvocation属性

   清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。使用beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素

   @CacheEvict(value="users", beforeInvocation=true)

   public void delete(Integer id) {

      System.out.println("delete user by id: " + id);

   }

二  操作案例

2.1 工程结构

2.2 pom文件

    <!-- 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 service

1.接口

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);public void addUser(Users u);
}

2.实现类

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.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
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 {@Autowiredprivate 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.pageSizepublic Page<Users> findUserByPage(Pageable pageable ){return this.userRepository.findAll(pageable);}//@CacheEvict(value="users",allEntries = true)  //清除缓存public void addUser(Users u){this.userRepository.save(u);}}

2.5 模型层

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.6 resources类

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的默认缓存策略  --><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.7 启动类

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 App
{public static void main( String[] args ){SpringApplication.run(App.class, args);System.out.println( "Hello World!" );}
}

2.8 test类

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={App.class})   //springboot的启动类
public class AppTest 
{@Autowiredprivate UserService us;@Testpublic void query(){List<Users> list=us.findUserAll();System.out.println("第1次 数据size:"+list.size()+" "+list.get(list.size()-1).getAddress());List<Users> list2=us.findUserAll();System.out.println("第2次 数据size:"+list2.size()+" "+list2.get(list2.size()-1).getAddress());System.out.println("====================================");Users u=new Users();u.setId(45);u.setAge(34);u.setName("湖北");u.setAddress("123");System.out.println("添加数据。。。。。。");us.addUser(u);List<Users> list3=us.findUserAll();System.out.println("第3次 数据size:"+list3.size()+" "+list3.get(list3.size()-1).getAddress());}
}

可以看到:进行了新增数据后,再次执行查询,还是查询内存的数据,数据旧数据,这样新增的数据,并没有查询出来。解决办法,需要清除一下缓存。重新加载新数据 

2.9 添加 @CacheEvict清除缓存

执行新增方法后,清除缓存数据,再次查询,直接查询mysql数据库中最新的数据,达到我们的目标

 

 

这篇关于springboot的ehcache的@CacheEvict清除缓存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

Spring 依赖注入与循环依赖总结

《Spring依赖注入与循环依赖总结》这篇文章给大家介绍Spring依赖注入与循环依赖总结篇,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. Spring 三级缓存解决循环依赖1. 创建UserService原始对象2. 将原始对象包装成工

Java中如何正确的停掉线程

《Java中如何正确的停掉线程》Java通过interrupt()通知线程停止而非强制,确保线程自主处理中断,避免数据损坏,线程池的shutdown()等待任务完成,shutdownNow()强制中断... 目录为什么不强制停止为什么 Java 不提供强制停止线程的能力呢?如何用interrupt停止线程s

SpringBoot请求参数传递与接收示例详解

《SpringBoot请求参数传递与接收示例详解》本文给大家介绍SpringBoot请求参数传递与接收示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录I. 基础参数传递i.查询参数(Query Parameters)ii.路径参数(Path Va

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp

Java MCP 的鉴权深度解析

《JavaMCP的鉴权深度解析》文章介绍JavaMCP鉴权的实现方式,指出客户端可通过queryString、header或env传递鉴权信息,服务器端支持工具单独鉴权、过滤器集中鉴权及启动时鉴权... 目录一、MCP Client 侧(负责传递,比较简单)(1)常见的 mcpServers json 配置

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映

Java Stream 并行流简介、使用与注意事项小结

《JavaStream并行流简介、使用与注意事项小结》Java8并行流基于StreamAPI,利用多核CPU提升计算密集型任务效率,但需注意线程安全、顺序不确定及线程池管理,可通过自定义线程池与C... 目录1. 并行流简介​特点:​2. 并行流的简单使用​示例:并行流的基本使用​3. 配合自定义线程池​示

从原理到实战解析Java Stream 的并行流性能优化

《从原理到实战解析JavaStream的并行流性能优化》本文给大家介绍JavaStream的并行流性能优化:从原理到实战的全攻略,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的... 目录一、并行流的核心原理与适用场景二、性能优化的核心策略1. 合理设置并行度:打破默认阈值2. 避免装箱

解决升级JDK报错:module java.base does not“opens java.lang.reflect“to unnamed module问题

《解决升级JDK报错:modulejava.basedoesnot“opensjava.lang.reflect“tounnamedmodule问题》SpringBoot启动错误源于Jav... 目录问题描述原因分析解决方案总结问题描述启动sprintboot时报以下错误原因分析编程异js常是由Ja