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

发布于:2024-05-03 ⋅ 阅读:(124) ⋅ 点赞:(0)

概述

在这里插入图片描述

1. Ehcache 2.x 缓存

1.1 SpringBoot整合Ehcache缓存

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

 spring.cache.ehcache.config=classpath:config/another-config.xml

在这里插入图片描述

1.2 应用:缓存方法

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

@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,
代码如下:

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

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2. Redis实现

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

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


网站公告

今日签到

点亮在社区的每一天
去签到