SpringBoot集成Redis及SpringCache緩存管理示例詳解
1.集成Redis
1.導入依賴
<!--spirngboot springdata對redis支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.配置信息
#數(shù)據(jù)源配置
spring:
redis:
database: 0
host: 127.0.0.1
port: 6379
password: 123456
jedis:
pool:
max-wait: 2000ms
max-active: 83.注入redisTemplate使用
@RunWith(SpringRunner.class) //使用springboot2.6.13的版本可以省略這個注解
@SpringBootTest(classes = App.class) //如果測試類和啟動不在同一個包下classes必須要寫
public class SpringbootDataRedisApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void test() throws Exception{
redisTemplate.opsForValue().set("name","zs");
System.out.println(redisTemplate.opsForValue().get("name"));
}
}4.自定義配置redis中key和value的序列化
@Configuration
public class RedisConfig {
// 注入Redis連接工廠
@Resource
private RedisConnectionFactory factory;
/**
* @Description: 自定義RedisTemplate對象注入Bean容器中
* @Author: Neuronet
* @Date: 2023/10/22 18:49
**/
@Bean
public RedisTemplate<Object, Object> redisTemplate() {
// 1.創(chuàng)建一個RedisTemplate對象
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
// 2.指定Redis連接工廠
redisTemplate.setConnectionFactory(factory);
// 3.創(chuàng)建一個JSON格式序列化對象,此處使用的是Redis自己的的序列化器
GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
// 4.指定除開hash數(shù)據(jù)類型之外的數(shù)據(jù)key和value使用什么序列化器
redisTemplate.setKeySerializer(serializer);
redisTemplate.setValueSerializer(serializer);
// 5.指定hash數(shù)據(jù)類型的key和value序列化器
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(serializer);
return redisTemplate;
}
} 2.SpringCahe緩存管理
1. SpringCache概述
Spring 3.1 引入了激動人心的基于注解(annotation)的緩存(cache)技術,它本質上不是一個具體的緩存實現(xiàn)方案(比如EHCache 或者 OSCache),而是一個對緩存使用的抽象,通過在既有代碼中加入少量它定義的各種 annotation,即能夠達到緩存方法的返回對象的效果
Spring 的緩存技術還具備相當?shù)撵`活性。不僅能夠使用 SpEL(Spring Expression Language)來定義緩存的 key 和各種 condition,還提供開箱即用的緩存暫時存儲方案,也支持和主流的專業(yè)緩存比如 EHCache 集成
說人話:SpringCahce對緩存流程進行了簡化封裝,提供了一些注解,我們通過簡單的打注解就能實現(xiàn)緩存的添加,修改,刪除等,注解如下:
- @Cacheable:觸發(fā)緩存寫入
- @CacheEvict:觸發(fā)緩存清除
- @CachePut:更新緩存(不會影響到方法的運行)
- @Caching:重新組合要應用于方法的多個緩存操作
- @CacheConfig:設置類級別上共享的一些常見緩存設置
2.SpringCache大致原理
1.Spring Cache利用了AOP,實現(xiàn)了基于注解的緩存功能,并且進行了合理的抽象,業(yè)務代碼不用關心底層是使用了什么緩存框架,只需要簡單地加一個注解,就能實現(xiàn)緩存功能了,做到了對代碼侵入性做小。
2.由于市面上的緩存工具實在太多,SpringCache框架還提供了CacheManager接口,可以實現(xiàn)降低對各種緩存框架的耦合。它不是具體的緩存實現(xiàn),它只提供一整套的接口和代碼規(guī)范、配置、注解等,用于整合各種緩存方案,比如Caffeine、Guava Cache、Ehcache。

3.SpringCache注解
3.1. @Cacheable:寫緩存
方式一:@Cacheable可以用來進行緩存的寫入,先也會根據(jù)緩存名和key去查詢,如果沒有查詢到,自動將方法的返回結果存儲在緩存中,以便于在后續(xù)調用的時候可以直接返回緩存中的值,而不必再執(zhí)行實際的方法
@Cacheable(cacheNames=“books”,key=”'book1'”) // books::book1
public Book findBook(ISBN isbn) {.
//查詢數(shù)據(jù)庫
return 數(shù)據(jù);
}方式二:一個方法可以對應多個緩存名稱
@Cacheable(cacheNames={“books”, “isbns”},key=”'book1'”)
public Book findBook(ISBN isbn) {..…}方式三@Cacheable的緩存名稱是可以配置動態(tài)參數(shù)的,比如選擇傳入的參數(shù),如下: (以下示例是使用SpEL聲明,如果您不熟悉SpEL,可以閱讀Spring Expression Language)
@Cacheable(cacheNames=“books”, key=“#isbn”) //參數(shù)值作為Key public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed) @Cacheable(cacheNames=“books”, key=“#isbn.rawNumber”) public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
方式四
@Cacheable還可以設置根據(jù)條件判斷是否需要緩存
condition:取決于給定的參數(shù)是否滿足條件 unless:取決于返回值是否滿足條件(除非)
以下是一個簡單的例子:key有默認的名字
@Cacheable(cacheNames=“book”, condition=“#name.length() < 32”) public Book findBook(String name) @Cacheable(cacheNames=“book”,condition=“#name.length()<32”, unless=“#result.hardback”) public Book findBook(String name)
3.2. @CachePut:修改緩存
@CachePut:當需要更新緩存而不干擾方法的運行時 ,可以使用該注解。也就是說,始終執(zhí)行該方法,并將結果放入緩存(已經(jīng)有緩存就更新緩存),注解參數(shù)與@Cacheable相同。 以下是一個簡單的例子:
@CachePut(cacheNames="book", key="#isbn")
public Book updateBook(ISBN isbn, BookDescriptor descriptor) {
}通常強烈建議不要對同一方法同時使用@CachePut和@Cacheable注解,因為它們具有不同的行為??赡軙a(chǎn)生不可思議的BUG哦
3.3. @CacheEvict:刪除緩存
@CacheEvict:刪除緩存的注解,這對刪除舊的數(shù)據(jù)和無用的數(shù)據(jù)是非常有用的。這里還多了一個參數(shù)(allEntries),設置allEntries=true時,可以對整個條目進行批量刪除。 以下是個簡單的例子:
@CacheEvict(cacheNames="books", key="'book1'") public void loadBooks(InputStream batch) //對cacheNames進行批量刪除 @CacheEvict(cacheNames="books", allEntries=true) public void loadBooks(InputStream batch)
3.4. @Caching:組合注解
@Caching在使用緩存的時候,有可能會同時進行更新和刪除,會出現(xiàn)同時使用多個注解的情況。而@Caching可以實現(xiàn)。 以下是個簡單的例子:
@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") })
public Book importBooks(String deposit, Date date)3.5. @CacheConfig: 統(tǒng)一配置
@CacheConfig:緩存提供了許多的注解選項,但是有一些公用的操作,我們可以使用@CacheConfig在類上進行全局設置。 以下是個簡單的例子:
@CacheConfig(cacheName="books")
public class BookRepositoryImpl implements BookRepository {
//注意:如果沒有指定key的話,keyGenerator會自動生成key導致刪除緩存失敗,所以下面的緩存操作需要指定key
@Cacheable(key="'book1'")
public Book findBook(ISBN isbn) {...}
}4.SpringCache實戰(zhàn)
1.導入依賴
<!-- SpringCache依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
2.配置SpringCache集成redis
/**
* @Description: SpringCache配置
* @Author: Neuronet
* @Date: 2023/10/22 19:32
**/
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
@Resource
private RedisConnectionFactory factory;
@Bean
@Override
public CacheResolver cacheResolver() {
return new SimpleCacheResolver(cacheManager());
}
@Bean
@Override
public CacheErrorHandler errorHandler() {
// 用于捕獲從Cache中進行CRUD時的異常的回調處理器。
return new SimpleCacheErrorHandler();
}
//緩存管理器
@Bean
@Override
public CacheManager cacheManager() {
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.disableCachingNullValues() //不允許空值
.serializeValuesWith(RedisSerializationContext.SerializationPair
//值使用JSON序列化
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();
}
}3.開啟springCache
在啟動類注解:@EnableCaching
4.添加緩存
緩存注解不能加在內部方法上,比如:方法A調用方法B,給方法B加上緩存注解會失效,因為內部方法調用代理會失效,在A方法上打注解即可
//會先根據(jù)articleType::typeTree從redis獲取,如果有直接用緩存的。如果沒有就執(zhí)行方法體的代碼查詢數(shù)據(jù)庫
@Cacheable(cacheNames = "articleType", key = "'typeTree'")
public List<ArticleType> getTypeTree() {
Object obj = redisTemplate.opsForValue().get("typeTree");
if(obj == null){//redis沒有
List<ArticleType> typeTree = typeTree();
redisTemplate.opsForValue().set("typeTree",typeTree);
return typeTree;
}
return typeTree();
}到此這篇關于SpringBoot集成Redis及SpringCache緩存管理的文章就介紹到這了,更多相關SpringBoot集成Redis內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringMVC 重定向參數(shù)RedirectAttributes實例
這篇文章主要介紹了SpringMVC 重定向參數(shù)RedirectAttributes實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
IntelliJ IDEA基于Scala實現(xiàn)Git檢查工具
這篇文章主要介紹了如何使用Scala實現(xiàn)自定義的Git檢查工具,大家可以基于本文的示例進行擴展與實現(xiàn),也可以進行其他應用方向的嘗試,感興趣的可以了解下2023-08-08
Spring Boot 開發(fā)環(huán)境熱部署詳細教程
這篇文章主要介紹了Spring Boot 開發(fā)環(huán)境熱部署,本文給大家介紹了Spring Boot 開發(fā)環(huán)境熱部署的原理及快速配置方法,通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
詳解Spring Boot應用的啟動和停止(start啟動)
這篇文章主要介紹了詳解Spring Boot應用的啟動和停止(start啟動),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12

