第九章 SpringBoot缓存-方法的缓存❤❤

第九章 SpringBoot缓存-方法的缓存

  • 概述
  • [1. Ehcache 2.x 缓存](#1. Ehcache 2.x 缓存)
    • [1.1 SpringBoot整合Ehcache缓存](#1.1 SpringBoot整合Ehcache缓存)
    • [1.2 应用:缓存方法](#1.2 应用:缓存方法)
      • [缓存方法注解的使用 ❤❤❤](#缓存方法注解的使用 ❤❤❤)
  • [2. Redis实现](#2. Redis实现)
  • ***************************************

概述

1. Ehcache 2.x 缓存

1.1 SpringBoot整合Ehcache缓存

java 复制代码
<dependency> 
	<groupId>org. springframework. boot</groupId> 
	<artifactId>spring-boot-starter-cache</artifactId> 
</dependency> 
<dependency> 
	<groupId>net.sf.ehcache</groupId> 
	<artifactid>ehcache</artifactid> 
</dependency> 
<dependency> 
	<groupId>org.springframework.boot</groupId> 
	<artifactid>spring-boot-starter-web</artifactid> 
</dependency> 
xml 复制代码
<ehcache>
<diskStore path="java.io.tmpdir/cache"/>
<defaultCache
		maxElementsInMemory="10000"
		eternal="false"
		timeToIdleSeconds="120"
		timeToLiveSeconds="120"
		overflowToDisk="false"
		diskPersistent="false"
		diskExpiryThreadIntervalSeconds="120"
	/>
<cache name="book_cache"
		maxElementsInMemory="10000"
		eternal="true"
		timeToIdleSeconds="120"
		timeToLiveSeconds="120"
		overflowToDisk="true"
		diskPersistent="true"
		diskExpiryThreadIntervalSeconds="600"
	/>
</ehcache>
java 复制代码
 spring.cache.ehcache.config=classpath:config/another-config.xml

1.2 应用:缓存方法

缓存方法注解的使用 ❤❤❤

java 复制代码
@Repository
@CacheConfig(cacheNames ="book_cache")
public class BookDao {
	@Cacheable
	public Book getBookById(Integer id){
		System.out.println("getBookById");
		Book book = new Book();
		book.setId(id);
		book.setName("三国演义");
		book.setAuthor("罗贯中");
		return book;
	}
	
	@CachePut(key ="#book.id")
	public Book updateBookById(Book book){
		System.out.println("updateBookById");
		book.setName("三国演义2");
		return book;
	}
	
	@CacheEvict(key ="#id")
	public void deleteBookById(Integer id){
		System.out.println("deleteBookById");
	}
}



自定义缓存key生成器

如果这些key不能够满足开发需求,开发者也可以自定义缓存key的生成器KeyGenerator,

代码如下:

java 复制代码
@Component
public class MyKeyGenerator implements KeyGenerator {
	@Override
	public Object generate(Object target,Method method,object... params){
		return Arrays.tostring(params);
	}
}



2. Redis实现


***************************************

相关推荐
青山木7 小时前
Hot 100 ---腐烂的橘子
java·数据结构·后端·算法·leetcode·广度优先
卷无止境7 小时前
Python的collections模块:那些被低估的"瑞士军刀"
后端·python
卷无止境7 小时前
Python的方法解析顺序:一场关于继承顺序的精妙设计
后端·python
ruleslol7 小时前
SpringBoot26-@Configuration + @Component
spring boot
宁&沉沦7 小时前
Chrome 扩展 Manifest 字段版本支持一览(全量)
前端·后端·编辑器
吃饱了得干活8 小时前
缓存与数据库一致性:从理论到实战
java·后端·面试
520拼好饭被践踏8 小时前
JAVA+Agent学习day22
java·开发语言·后端·学习
whi8 小时前
V 编译器 v3 ownership 模式:编译与使用指南
后端·编译器
swipe8 小时前
05|(前端转后全栈)不手写一堆 SQL,后端怎么操作数据库?MyBatis-Plus 入门
前端·后端·全栈
霸道流氓气质8 小时前
SpringBoot中使用JasperReports 报表引擎 — 介绍、原理与使用实践
java·spring boot·后端