您好,登錄后才能下訂單哦!
springboot中怎么操作redis緩存,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。
引入依賴庫(kù)
在pom中引入依賴庫(kù),如下
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId></dependency>
注解使用
@Cacheable@Cacheable("product")@Cacheable(value = {"product","order"}, key = "#root.targetClass+'-'+#id")@Cacheable(value = "product", key = "#root.targetClass+'-'+#id")
自定義cacheManager
@Cacheable(value = "product", key = "#root.targetClass+'-'+#id” cacheManager="cacheManager")@CachePut
應(yīng)用到寫數(shù)據(jù)的方法上,如新增/修改方法
@CachePut(value = "product", key = "#root.targetClass+'-'+#product.id")@CacheEvict
即應(yīng)用到移除數(shù)據(jù)的方法上,如刪除方法
@CacheEvict(value = "product", key = "#root.targetClass+'-'+#id")
提供的SpEL上下文數(shù)據(jù)
Spring Cache提供了一些供我們使用的SpEL上下文數(shù)據(jù),下表直接摘自Spring官方文檔:
methodName root對(duì)象 當(dāng)前被調(diào)用的方法名 #root.methodName method root對(duì)象 當(dāng)前被調(diào)用的方法 #root.method.name target root對(duì)象 當(dāng)前被調(diào)用的目標(biāo)對(duì)象 #root.target targetClass root對(duì)象 當(dāng)前被調(diào)用的目標(biāo)對(duì)象類 #root.targetClass args root對(duì)象 當(dāng)前被調(diào)用的方法的參數(shù)列表 #root.args[0] caches root對(duì)象 當(dāng)前方法調(diào)用使用的緩存列表(如@Cacheable(value={"cache1", "cache2"})),則有兩個(gè)cache #root.caches[0].name argument name 執(zhí)行上下文 當(dāng)前被調(diào)用的方法的參數(shù),如findById(Long id),我們可以通過#id拿到參數(shù) #user.id result 執(zhí)行上下文 方法執(zhí)行后的返回值(僅當(dāng)方法執(zhí)行之后的判斷有效,如‘unless','cache evict'的beforeInvocation=false) #result
自定義Cache配置
@Configuration@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport { /** * 自定義redis key值生成策略 */ @Bean @Override public KeyGenerator keyGenerator() { return (target, method, params) -> { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); }; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(Object
名字 | 位置 | 描述 | 示例 |
---|
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。