




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、redis 系列三 -springboot 如何使用 redis 做緩存及緩存注解的 用法總結1. 概述本文介紹 spring boot 如何使用 Redis 做緩存,如何對 redis 緩存進行定制化配置 (如 key 的有效期 )以及 spring boot 如何 初始化 redis 做緩存。使用具體的代碼介紹了Cacheable,CacheEvict , CachePut, CacheConfig 等注解及其屬性 的用法。2. spring boot 集成 redis2.1. perties配置 perties ,包含如下信息:
2、指定緩存的類型配置 redis 的服務器信息請不要配置 spring.cache.cache-names值,原因后面再說# 緩存# spring.cache.cache-names=book1,book2 spring.cache.type=REDIS # REDIS (RedisProperties) spring.redis.database=0 spring.redis.host= spring.redis.password= spring.redis.port=6379 spring.redis.pool.max-idle=8 spring.redis.poo
3、l.min-idle=0 spring.redis.pool.max-active=100 spring.redis.pool.max-wait=-1123456789101112131234567891 01112132.2. 配置啟動類EnableCaching: 啟動緩存重新配置RedisCacheManager,使用新的配置的值SpringBootApplicationEnableCaching / 啟動緩存 public class CacheApplication private static final Logger log =LoggerFactory.getLogger(Ca
4、cheApplication.class);public static void main(String args) ("Start CacheApplication. ");SpringApplication.run(CacheApplication.class, args);/* 重新配置 RedisCacheManager* param rd*/Autowiredpublic void configRedisCacheManger(RedisCacheManagerrd)rd.setDefaultExpiration(100L); 1234567891
5、01112131415161718192012345678910111213141 51617181920經(jīng)過以上配置后, redis 緩存管理對象已經(jīng)生成。下面簡單介 紹 spring boot 如何初始化 redis 緩存。2.3. spring boot 如何初始化 redis 做緩存緩存管理接口 org.springframework.cache.CacheManager , spring boot 就是通過此類實現(xiàn)緩存的管理。 redis 對應此接口 的實現(xiàn)類是org.springframework.data.redis.cache.RedisCacheManager 。下 面介紹此
6、類如何生成。首先我們配置 perties 的 spring.redis.* 屬性后 EnableCaching 后, spring 會執(zhí)行 RedisAutoConfiguration , 初始化 RedisTemplate 和 StringRedisTemplate ConfigurationConditionalOnClass( JedisConnection.class, RedisOperations.class, Jedis.class )EnableConfigurationProperties(RedisProperties.class)public
7、 class RedisAutoConfiguration /* Standard Redis configuration.*/Configurationprotected static class RedisConfiguration BeanConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException RedisTem
8、plate template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory);return template;BeanConditionalOnMissingBean(StringRedisTemplate.class) public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException StringRedisTemp
9、late template = newStringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;12345678910111213141516171819202122232425262728293031323334123456789101112131415161718192021222324252627 28293031323334然后 RedisCacheConfiguration 會將 RedisAutoConfiguration 生 成的 RedisTemplat
10、e 注入方法生成 RedisCacheManager 后。 ConfigurationAutoConfigureAfter(RedisAutoConfiguration.class)ConditionalOnBean(RedisTemplate.class)ConditionalOnMissingBean(CacheManager.class)Conditional(CacheCondition.class)class RedisCacheConfiguration private final CacheProperties cacheProperties;private final Cach
11、eManagerCustomizers customizerInvoker;RedisCacheConfiguration(CachePropertiescacheProperties,CacheManagerCustomizers customizerInvoker) this.cacheProperties = cacheProperties; this.customizerInvoker = customizerInvoker;Beanpublic RedisCacheManager cacheManager(RedisTemplate redisTemplate) RedisCache
12、Manager cacheManager = newRedisCacheManager(redisTemplate); cacheManager.setUsePrefix(true);List cacheNames =this.cacheProperties.getCacheNames();if (!cacheNames.isEmpty() cacheManager.setCacheNames(cacheNames);returnthis.customizerInvoker.customize(cacheManager);123456789101112131415161718192021222
13、324252627282930123456789101112131415161718192021222324252627282930 根據(jù)以上的分析,我們知道在 spring 已經(jīng)幫我們生成一個 RedisCacheManager 并進行了配置。最后我們再可以對這個 RedisCacheManager 進行二次配置, 這里只列出配置 key 的有效期/* 重新配置 RedisCacheManager* param rd*/Autowiredpublic void configRedisCacheManger(RedisCacheManager rd)rd.setDefaultExpiratio
14、n(100L);123456789123456789請不要在 perties 中配置:spring.cache.cache-names=book1,book2,否貝U會導致我們新的 配置無法作用到這些配置的cache上。這是因為RedisCacheConfiguration 初始化 RedisCacheManager 后,會 立即調用RedisCacheConfiguration的初始化cache,而此時 configRedisCacheManger 還沒有執(zhí)行此方法,使得我們的配 置無法啟作用。反之,如果不配置,則后創(chuàng)建cache,會使用我們的配置。3. spri
15、ng 緩存注解的用法上節(jié)已經(jīng)介紹如何配置緩存,這節(jié)介紹如何使用緩存3.1 輔助類下方會使用到的輔助類Book:public class Book implements Serializable private static final long serialVersionUID =2629983876059197650L;private String id;private String name; / 書名 private Integer price; / 價格 private Date update; /public Book(String id, String name, Integer
16、price, Date update) super();this.id = id; = name;this.price = price;this.update = update;/ set/get 略1234567891011121314151617181234567891011121314151617 18BookQry : 封裝請求類 public class BookQry private String id;private String name; / 書名/ set/get 略 12345671234567AbstractService抽象類:初始化 reposit
17、oryBook 值,模擬數(shù)據(jù)庫數(shù)據(jù)。BookService 和 BookService2 都是繼承此類 public abstract class AbstractService protected static Map repositoryBook = new HashMap();public AbstractService() super();PostConstruct public void init() / 1Book book1 = new Book("1", "name_1", 11, new Date();repositoryBook.pu
18、t(book1.getId(), book1);/ 2Book book2 = new Book("2", "name_2", 11, new Date();repositoryBook.put(book2.getId(), book2);/ 3Book book3 = new Book("3", "name_3", 11, new Date();repositoryBook.put(book3.getId(), book3);/ 4Book book4 = new Book("4", &quo
19、t;name_4", 11, new Date();repositoryBook.put(book4.getId(), book4);123456789101112131415161718192021222324251234567891 01112131415161718192021222324253.2. Cacheable Cacheable 的屬性的意義cacheNames:指定緩存的名稱key:定義組成的key值,如果不定義,則使用全部的參數(shù)計 算一個 key 值。可以使用 spring El 表達式* cacheNames 設置緩存的值* key:指定緩存的key,這是指參
20、數(shù)id值。key可 以使用 spEl 表達式* param id* return*/Cacheable(cacheNames="book1", key="#id")public Book queryBookCacheable(String id) ("queryBookCacheable,id=",id); return repositoryBook.get(id);/*這里使用另一個緩存存儲緩存* param id* return*/Cacheable(cacheNames="book2",
21、 key="#id") public Book queryBookCacheable_2(String id) ("queryBookCacheable_2,id=",id); return repositoryBook.get(id);* 緩存的 key 也可以指定對象的成員變量* param qry* return*/Cacheable(cacheNames="book1", key="#qry.id")public Book queryBookCacheableByBookQry(Boo
22、kQry qry) ("queryBookCacheableByBookQry,qry=",qry);String id = qry.getId();Assert.notNull(id, "id can't be null!");String name = qry.getName();Book book = null; if(id != null)book = repositoryBook.get(id);if(book != null && !(name != null &&book.get
23、Name().equals(name)book = null;return book;12345678910111213141516171819202122232425262728 2930313233343536373839404142434412345678910111213141 516171819202122232425262728293031323334353637383940 41424344 keyGenerator:定義key生成的類,和 key的不能同時存在/*以上我們使用默認的keyGenerator,對應spring的SimpleKeyGenerator* 如果你的使用很
24、復雜,我們也可以自定義myKeyGenerator 的生成 keykey 和 keyGenerator 是互斥,如果同時制定會出異* The key and keyGenerator parameters are mutually exclusive and an operation specifying both will result in an exception.* param id* return*/Cacheable(cacheNames="book3", keyGenerator="myKeyGenerator")public Book q
25、ueryBookCacheableUseMyKeyGenerator(String id)("queryBookCacheableUseMyKeyGenerator,id=",i d);return repositoryBook.get(id);/ 自定義緩存 key 的生成類實現(xiàn)如下: Componentpublic class MyKeyGenerator implements KeyGenerator Overridepublic Object generate(Object target, Method method,Object. param
26、s) System.out.println(" 自定義緩存, 使用第一參數(shù)作為 緩存 key. params = " + Arrays.toString(params);/ 僅僅用于測試,實際不可能這么寫return params0 + "0"123456789101112131415161718192021222324252627281234 5678910111213141516171819202122232425262728sync:如果設置sync=true: a.如果緩存中沒有數(shù)據(jù),多個線 程同時訪問這個方法,則只有一個方法會執(zhí)行到方法,其它
27、方法需要等待 ; b. 如果緩存中已經(jīng)有數(shù)據(jù),則多個線程可以 同時從緩存中獲取數(shù)據(jù)如果設置 sync=true,如果緩存中沒有數(shù)據(jù),多個線程同時訪問這個方 法,則只有一個方法會執(zhí)行到方法,其它方法需要等待* 如果緩存中已經(jīng)有數(shù)據(jù),則多個線程可以同時從緩 存中獲取數(shù)據(jù)* param id* return*/Cacheable(cacheNames="book3", sync=true) public Book queryBookCacheableWithSync(String id) ("begin .queryBookCacheableByB
28、ookQry,id=",id);try Thread.sleep(1000 * 2); catch (InterruptedException e) ("end .queryBookCacheableByBookQry,id=",id);return repositoryBook.get(id);12345678910111213141516171234567891011121314151 617 condition 和 unless 只滿足特定條件才進行緩存:condition: 在執(zhí)行方法前, condition 的值為 true ,則緩
29、存數(shù)據(jù) unless :在執(zhí)行方法后,判斷unless,如果值為true,則不緩存數(shù)據(jù)conditon和unless可以同時使用,則此時只緩存同時滿足兩 者的記錄/* 條件緩存:* 只有滿足 condition 的請求才可以進行緩存,如果不滿足條件,則跟方法沒有 Cacheable 注解的方法一樣* 如下面只有 id < 3 才進行緩存*/Cacheable(cacheNames="book11",condition="T(java.lang.Integer).parseInt(#id) < 3 ")public Book queryBook
30、CacheableWithCondition(String id)("queryBookCacheableByBookQry,id=",id);return repositoryBook.get(id);/*條件緩存:對不滿足 unless 的記錄,才進行緩存"unless expressions" are evaluated after the method has been called* 如下面:只對不滿足返回'T(java.lang.Integer).parseInt(#result.id) <3 '
31、的記錄進行緩存* param id* return*/Cacheable(cacheNames="book22", unless ="T(java.lang.Integer).parseInt(#result.id) <3 ")public Book queryBookCacheableWithUnless(String id) ("queryBookCacheableByBookQry,id=",id);return repositoryBook.get(id);123456789101112131415
32、16171819202122232425123456 789101112131415161718192021222324253.3. CacheEvict刪除緩存allEntries = true: 清空緩存 book1 里的所有值allEntries = false: 默認值,此時只刪除 key 對應的值/* allEntries = true: 清空 book1 里的所有緩存*/CacheEvict(cacheNames="book1", allEntries=true) public void clearBook1All()("clea
33、rAll");/* 對符合 key 條件的記錄從緩存中 book1 移除*/CacheEvict(cacheNames="book1", key="#id") public void updateBook(String id, String name) ("updateBook"); Book book = repositoryBook.get(id); if(book != null) book.setName(name); book.setUpdate(new Date();12345678910111213141516171819123456789101112131415161718193.4. CachePut 每次執(zhí)行都會執(zhí)行方法,無論緩存里是否有值,同時使用新 的返回值的替換緩存中的值。這里不同于Cacheable:Cacheable 如果緩存沒有值, 從則執(zhí)行方法并緩存數(shù)據(jù), 如 果緩存有值,則從緩存中獲取值CachePut(cacheNames="book1", key="#id") public Book queryBookCachePut(String id) ("queryBook
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年房屋銷售中介租賃合同樣本
- 簡易版貨物買賣合同范本大全
- 國際商會國際分銷示范合同(針對消費電子產(chǎn)品)
- 2025年全球產(chǎn)品許可合同
- 2025年中等專業(yè)學校教師招聘合同樣例
- 建筑工程合同違約起訴狀
- 國際技術交流合作合同示例
- 管道維修服務合同
- 重點工程項目貨物供應合同
- 產(chǎn)權及使用權轉讓合同書
- 食品檢驗員聘用合同樣本
- 六年級信息技術下冊教學計劃
- 2025年九年級數(shù)學中考復習計劃
- 2023年長沙自貿投資發(fā)展集團有限公司招聘筆試真題
- 《物料擺放規(guī)范》課件
- 2024年資助政策主題班會課件
- 《煙花效果及制作》課件
- 2024江蘇太倉市城市建設投資集團限公司招聘易考易錯模擬試題(共500題)試卷后附參考答案
- 2024年全新統(tǒng)計法培訓課件:普法教育新方向
- 保育教育評估指南
- 現(xiàn)代康復治療腕管綜合癥
評論
0/150
提交評論