@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进行说明的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 判断java中String、自定义对象、
- 下一篇: 利用线程池为线程创建一个守护线程