快取 SpringCache 自定義快取配置

2021-10-09 06:55:09 字數 1455 閱讀 5604

redis 預設使用 jdk 序列化,需要我們配置序列化機制,自定義乙個配置類,否則存入的資料顯示亂碼

@enablecaching //開啟快取

@configuration

public class mycacheconfig

}

使用以上配置後,雖然亂碼的問題解決了,但配置檔案又不生效了,比如過期時間等,這是因為在初始化時會判斷使用者是否自定義了配置檔案,如果自定義了,原來的就不會生效,原始碼如下:

private org.springframework.data.redis.cache.rediscacheconfiguration

determineconfiguration(classloader classloader)

//沒配置使用預設的配置

redis redisproperties = this.cacheproperties.getredis();

org.springframework.data.redis.cache.rediscacheconfiguration config = org.springframework.data.redis.cache.rediscacheconfiguration

.defaultcacheconfig();

config = config.serializevalueswith(

serializationpair.fromserializer(new jdkserializationredisserializer(classloader)));

if (redisproperties.gettimetolive() != null)

if (redisproperties.getkeyprefix() != null)

if (!redisproperties.iscachenullvalues())

if (!redisproperties.isusekeyprefix())

return config;

}

所以,我們也需要手動獲取 ttl、prefix 等屬性,直接仿照原始碼就行,將配置類修改為如下:

@enablecaching //開啟快取

@configuration

@enableconfigurationproperties(cacheproperties.class) //快取的所有配置屬性都在這個類裡

public class mycacheconfig

if (redisproperties.getkeyprefix() != null)

if (!redisproperties.iscachenullvalues())

if (!redisproperties.isusekeyprefix())

return config;

}}

Spring Cache自定義快取格式

springcache是乙個基於註解來更新快取的元件,對於大多數的快取操作都適用,本質是基於aop實現,也不用再重複千輪子,直接使用便是,並且支援springel表示式,對於使用教程網上還是很多的。很多時候為了相容性以及方便,會把物件轉換成json格式存入快取 redis 中,這就需要對cache進...

使用springCache快取的步驟

org.springframework.cache.concurrent.concurrentmapcachemanager加入ioc容器,用 cachemanager會報錯.spring專案因為沒有concurrentmapcachemanage快取報錯,網上我一般沒看到有文章會說明。在配置類上加...

SpringCache加Redis做快取

org.springframework.bootgroupid spring boot starter data redisartifactid dependency org.apache.commonsgroupid commons pool2artifactid 2.6.0version dep...