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


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

相关推荐
ServBay22 分钟前
从代码到上线,Cursor Live Apps 能替独立开发者做什么
后端·ai编程·cursor
程序员cxuan25 分钟前
LobeHub 是真的夯,简直 Super-Agent 最佳实现。
人工智能·后端·程序员
挖坑的张师傅1 小时前
开源一个 Managed Agents 云端托管智能体平台
后端·agent
挖坑的张师傅1 小时前
Agent 基建系列:用 MCP Tunnel 让云端 Agent 访问企业内网工具
后端·agent
量化分析码农1 小时前
【Python量化多因子实战 04】因子暴露不是 alpha:市值与行业中性化实战
前端·后端
挖坑的张师傅1 小时前
开源 yourbatis:把 MyBatis 的动态 SQL 体验带到 Go
后端·agent
挖坑的张师傅1 小时前
Agent 基建系列:E2B Go SDK
后端·agent
挖坑的张师傅2 小时前
Agent 基建系列(二):基于 Proxy 的凭证不入沙箱和网络管控方案
后端·agent
挖坑的张师傅2 小时前
用 FUSE 为云端 Agent 构建文件系统
后端·agent
张彦峰ZYF2 小时前
放行、排队与拒绝:限流设计的算法选型、数据结构与并发代价
后端·架构·滑动窗口·漏桶·令牌桶·高并发+限流