第九章 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实现


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

相关推荐
风象南5 小时前
很多人说,AI 让技术平权了,小白也能乱杀老师傅 ?
人工智能·后端
雨中飘荡的记忆6 小时前
ElasticJob分布式调度从入门到实战
java·后端
Se7en2586 小时前
推理平台全景
后端
大漠_w3cpluscom7 小时前
你学不会 CSS,不是笨,是方向错了
后端
cipher10 小时前
ERC-4626 通胀攻击:DeFi 金库的"捐款陷阱"
前端·后端·安全
毅航11 小时前
自然语言处理发展史:从规则、统计到深度学习
人工智能·后端
JxWang0511 小时前
Task04:字符串
后端
树獭叔叔11 小时前
10-让模型更小更聪明,学而不忘:知识蒸馏与持续学习
后端·aigc·openai
JxWang0511 小时前
Task02:链表
后端