日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

@EnableCaching与@Cacheable的使用方法,结合redis进行说明

發布時間:2025/1/21 编程问答 52 豆豆
生活随笔 收集整理的這篇文章主要介紹了 @EnableCaching与@Cacheable的使用方法,结合redis进行说明 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1、兩者作用

首先說明這兩個注解都是spring提供的,可以結合不同的緩存技術使用。
@EnableCaching是開啟緩存功能,作用于緩存配置類上或者作用于springboot啟動類上。
@Cacheable 注解在方法上,表示該方法的返回結果是可以緩存的。也就是說,該方法的返回結果會放在緩存中,以便于以后使用相同的參數調用該方法時,會返回緩存中的值,而不會實際執行該方法。如果緩存過期,則重新執行。

結合redis介紹如何使用

1、首先給出redis的配置類

import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;@Configuration @EnableCaching public class BootRedisConfig{@Beanpublic CacheManager cacheManager(RedisConnectionFactory factory){//Duration.ofSeconds(120)設置緩存默認過期時間120秒RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(120));//解決使用@Cacheable,redis數據庫value亂碼config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));RedisCacheManager cacheManager = RedisCacheManager.builder(factory).cacheDefaults(config).build();return cacheManager;}@Beanpublic RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();//連接redis服務器redisTemplate.setConnectionFactory(factory);//將redis默認序列化方式轉換為json格式Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);//redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);return redisTemplate;} }

2、準備個實體類:

@Data public class Student implements Serializable {private String name;private int age; }

3、做個簡單測試:

@RestController @RequestMapping("/cache") public class CacheController { @GetMapping("/findById/{id}")@Cacheable("student00")public Student findById(@PathVariable("id")String id){Student student = new Student();student.setAge(23);student.setName("zhangsan");return student;} }

執行findById,@Cacheable(“student00”)使返回結果緩存到redis(配置了redis),結果以key為student00::{傳入參數id},value為返回的student對象。下次執行該方法時先根據id與student00拼串進行判斷緩存中是否有對應的key,有的話直接返回結果。

定義多個緩存名,會存多份

@GetMapping("/findByIds/{id}") @Cacheable({"student01","student02"}) public Student findByIds(@PathVariable("id")String id){Student student = new Student();student.setAge(25);student.setName("lisi");return student; }

另外,默認的key拼串并不是很友好,調用的方法只有一個參數時,會自動使用@Cacheable(“student00”)中設置的student00 + :: + 傳入參數;當多個參數時:

@GetMapping("/findById/{id}/{name}") @Cacheable("student00") public Student findById(@PathVariable("id")String id,@PathVariable("name")String name){Student student = new Student();student.setAge(23);student.setName("zhangsan");return student; }

為了更直觀,可以顯式指定key,利用SpEL(Spring Expression Language,Spring 表達式語言)來動態拼接key:

@Cacheable(value = "student00",key = "'id-name:' + #id + '-' + #name")

此外,@Cacheable()中還可加入sync = true/false屬性,
在一個多線程的環境中,某些操作可能被相同的參數并發地調用,這樣同一個 value 值可能被多次計算(或多次訪問 db),這樣就達不到緩存的目的。針對這些可能高并發的操作,我們可以使用 sync 參數來告訴底層的緩存提供者將緩存的入口鎖住,這樣就只能有一個線程計算操作的結果值,而其它線程需要等待,這樣就避免了 n-1 次數據庫訪問。

sync = true 可以有效的避免緩存擊穿的問題。

另外還可加入緩存判斷條件,對方法傳入參數進行判斷,滿足條件則執行緩存查詢;不滿足條件則直接把該方法當作普通方法使用,不會進行緩存判斷,也不會把結果放近緩存。

condition = “#id > 1” //只有id>1才走緩存

總結

以上是生活随笔為你收集整理的@EnableCaching与@Cacheable的使用方法,结合redis进行说明的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。