最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring cache整合redis代碼實(shí)例

 更新時(shí)間:2020年04月28日 11:50:17   作者:Terry  
這篇文章主要介紹了Spring cache整合redis代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

Spring-Cache是Spring3.1引入的基于注解的緩存技術(shù),本質(zhì)上它并不是一個(gè)具體的緩存實(shí)現(xiàn),而是一個(gè)對緩存使用的抽象,通過Spring AOP技術(shù),在原有的代碼上添加少量的注解來實(shí)現(xiàn)將這個(gè)方法轉(zhuǎn)成緩存方法的效果。

本來想來個(gè)分析源碼,奈何水平有限,先從實(shí)戰(zhàn)搞起。

先引入依賴:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
  <version>2.1.6.RELEASE</version>
</dependency>
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.9.3</version>
</dependency>

redis配置:

server:
 port: 8000

spring:
 redis:
  host: 23.95.x.x
  port: 6379
  timeout: 20s
  database: 0
  jedis:
   pool:
    max-active: 5
    max-idle: 3
    max-wait: 5s
  password: testtest

配置類:

package me.yanand.config;
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.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
@EnableCaching
public class RedisConfig{
 
  private Duration timeOut = Duration.ofMinutes(30);
  @Bean
  public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
        //設(shè)置緩存超時(shí)時(shí)間 30分鐘
        .entryTtl(timeOut)
        //設(shè)置key序列化方式
        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
        //設(shè)置value序列化方式
        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
        .disableCachingNullValues();
    return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config).transactionAware().build();
  }
}

主要看@EnableCaching注解,這個(gè)注解引入了@Import(CachingConfigurationSelector.class),通過CachingConfigurationSelector把代理創(chuàng)建類、CacheInterceptor、CacheOperationSource、BeanFactoryCacheOperationSourceAdvisor注入到容器,spring通過CacheInterceptor攔截器攔截相關(guān)帶有@Cacheable、@CacheEvict、@CachePut注解的方法并執(zhí)行相關(guān)緩存操作。

CacheInterceptor相關(guān)源碼:

@Nullable
private Object execute(final CacheOperationInvoker invoker, Method method, CacheOperationContexts contexts) {
 if (contexts.isSynchronized()) {
  CacheOperationContext context = contexts.get(CacheableOperation.class).iterator().next();
  //滿足條件執(zhí)行
  if (isConditionPassing(context, CacheOperationExpressionEvaluator.NO_RESULT)) {
   Object key = generateKey(context, CacheOperationExpressionEvaluator.NO_RESULT);
   Cache cache = context.getCaches().iterator().next();
   try {
     //這里主要看RedisCache的get方法
    return wrapCacheValue(method, cache.get(key, () -> unwrapReturnValue(invokeOperation(invoker))));
   }
   catch (Cache.ValueRetrievalException ex) {
    // The invoker wraps any Throwable in a ThrowableWrapper instance so we
    // can just make sure that one bubbles up the stack.
    throw (CacheOperationInvoker.ThrowableWrapper) ex.getCause();
   }
  }
  else {
   //不滿足直接執(zhí)行相關(guān)方法
   return invokeOperation(invoker);
  }
 }
 ...省略
}

RedisCache相關(guān)代碼:

public synchronized <T> T get(Object key, Callable<T> valueLoader) {
  ValueWrapper result = get(key);
        //緩存中有值則返回
  if (result != null) {
   return (T) result.get();
  }
        //緩存中不存在則執(zhí)行相關(guān)方法
  T value = valueFromLoader(key, valueLoader);
  put(key, value);
  return value;
 }

注解使用:

package me.yanand.dao;
import me.yanand.pojo.User;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class UserDao {
  @Cacheable(cacheNames = "users",key = "#root.targetClass+#name", unless = "#result eq null")
  public User getUser(String name){
    return new User("張三",30);
  }
  @CacheEvict(cacheNames = "users", key = "#root.targetClass+#name")
  public void delUser(String name){
  }
}

測試:

通過postman觸發(fā)相關(guān)方法,現(xiàn)在我們連上redis查看緩存寫入情況

這里我們看到key已經(jīng)寫入,過期時(shí)間也存在

現(xiàn)在我們刪除緩存

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • springboot-啟動bean沖突的解決

    springboot-啟動bean沖突的解決

    這篇文章主要介紹了springboot-啟動bean沖突的解決,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Java中CaffeineCache自定義緩存時(shí)間的實(shí)現(xiàn)

    Java中CaffeineCache自定義緩存時(shí)間的實(shí)現(xiàn)

    本文主要介紹了Java中CaffeineCache自定義緩存時(shí)間的實(shí)現(xiàn),通過聲明緩存value值holder對象并創(chuàng)建緩存容器,可以為不同的key值指定不同的過期時(shí)間,具有一定的參考價(jià)值,感興趣的可以了解一下
    2025-02-02
  • java實(shí)現(xiàn)雙色球機(jī)選號碼生成器

    java實(shí)現(xiàn)雙色球機(jī)選號碼生成器

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)雙色球機(jī)選號碼生成器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-01-01
  • Java 圖文并茂講解主方法中的String[] args參數(shù)作用

    Java 圖文并茂講解主方法中的String[] args參數(shù)作用

    很多老鐵不清楚JAVA主方法中main()里面的的參數(shù)是什么意思,以及有什么作用,接下來給大家用最通俗易懂的話來講解,還不清楚的朋友來看看吧
    2022-04-04
  • Postman form-data、x-www-form-urlencoded的區(qū)別及說明

    Postman form-data、x-www-form-urlencoded的區(qū)別及說明

    這篇文章主要介紹了Postman form-data、x-www-form-urlencoded的區(qū)別及說明,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2025-03-03
  • Spring Boot靜態(tài)資源路徑的配置與修改詳解

    Spring Boot靜態(tài)資源路徑的配置與修改詳解

    最近在做SpringBoot項(xiàng)目的時(shí)候遇到了“白頁”問題,通過查資料對SpringBoot訪問靜態(tài)資源做了總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-09-09
  • JDBC中Fetchsize的實(shí)現(xiàn)

    JDBC中Fetchsize的實(shí)現(xiàn)

    fetchsize是指在執(zhí)行數(shù)據(jù)庫查詢時(shí),每次從數(shù)據(jù)庫中獲取的記錄條數(shù),它對內(nèi)存使用和網(wǎng)絡(luò)傳輸效率有重要影響,在MyBatis中,可以通過全局設(shè)置或語句級別設(shè)置fetchsize,來控制查詢操作的內(nèi)存使用和提升性能,合理的fetchsize設(shè)置能有效減少網(wǎng)絡(luò)往返次數(shù)和防止內(nèi)存溢出
    2024-09-09
  • java中把字符串轉(zhuǎn)成 double的方法

    java中把字符串轉(zhuǎn)成 double的方法

    Java 中可以使用 Double 類中的靜態(tài)方法 parseDouble() 將一個(gè)字符串轉(zhuǎn)換為 double 類型的數(shù)值,本文結(jié)合實(shí)例代碼對java字符串轉(zhuǎn)成 double詳細(xì)講解,需要的朋友參考下吧
    2023-08-08
  • 詳談jvm--Java中init和clinit的區(qū)別

    詳談jvm--Java中init和clinit的區(qū)別

    下面小編就為大家?guī)硪黄斦刯vm--Java中init和clinit的區(qū)別。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-10-10
  • SpringBoot Test類注入失敗的解決

    SpringBoot Test類注入失敗的解決

    這篇文章主要介紹了SpringBoot Test類注入失敗的解決方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03

最新評論

南投市| 北宁市| 冕宁县| 益阳市| 江达县| 成都市| 襄城县| 东阿县| 正蓝旗| 大名县| 兴文县| 台前县| 吴桥县| 措美县| 赣榆县| 尼玛县| 峡江县| 哈尔滨市| 阜平县| 达州市| 鄂托克前旗| 古蔺县| 托克托县| 峨眉山市| 库车县| 拜泉县| 开平市| 纳雍县| 兴仁县| 澄江县| 九台市| 木兰县| 上杭县| 鹰潭市| 增城市| 咸丰县| 信阳市| 枞阳县| 新密市| 中山市| 婺源县|