2015-04-16 34 views
0

我對兩種方法使用了Spring的Redis和@Cacheable註解。當我調用一個方法時,我得到一個結果爲其他方法緩存。spring redis錯誤結果

當我爲使用@Cachebale批註的每種方法配置了不同的緩存時,如何從錯誤緩存中獲得結果?

設置:Spring版本4.1.6。 Redis數據1.5和Redis客戶端2.7.0。

示例代碼:

@Cacheable("test1") 
    public List<String> findSgsns() { 
} 

@Cacheable("test2") 
    public List<String> findSgsns2() { 
} 
+0

請更具體地處理您的問題。 – dunni

回答

0

問題通過加入下列設置到彈簧配置sloved(設置usePrefix):

<bean 
    id="cacheManager" 
    class="org.springframework.data.redis.cache.RedisCacheManager" 
    c:template-ref="redisTemplate"> 
    <property name="usePrefix" value="true" /> 
</bean> 
0

默認情況下,彈簧使用SimpleKeyGenerator來生成如果您沒有在@Cacheable註釋中指定它,則爲鍵。

public class SimpleKeyGenerator implements KeyGenerator { 

@Override 
public Object generate(Object target, Method method, Object... params) 
{ 
    return generateKey(params); 
} 

/** 
* Generate a key based on the specified parameters. 
*/ 
public static Object generateKey(Object... params) { 
    if (params.length == 0) { 
     return SimpleKey.EMPTY; 
    } 
    if (params.length == 1) { 
     Object param = params[0]; 
     if (param != null && !param.getClass().isArray()) { 
      return param; 
     } 
    } 
    return new SimpleKey(params); 
} 
} 

,因爲在您的兩個方法(findSgsns() and findSgsns2())沒有方法的參數,它本質上會產生兩種方法相同的緩存鍵。

你已經發現,基本上利用在redisTemplate豆,基本上你添加值(即「測試1」和「測試2」)在您的@Cacheable註釋指定usePrefix屬性時,它形成於緩存鍵的解決方案Redis的。我想提爲完整起見這裏2種選擇:

  1. 指定自己的密鑰對每種方法(注:你可以使用Spring EL指定你的鑰匙):

    @Cacheable(value = "test1", key = "key1") 
    public List<String> findSgsns() { 
    } 
    
    @Cacheable(value = "test2", key = "key2") 
    public List<String> findSgsns2() { 
    } 
    
  2. 構建定製密鑰生成器,和下面是樣品密鑰生成這需要方法名稱爲緩存redis的密鑰生成(注:定製密鑰生成器將通過擴展CachingConfigurerSupport類自動生效):

    @Configuration 
    public class RedisConfig extends CachingConfigurerSupport { 
    
    @Bean 
    public KeyGenerator keyGenerator() { 
        return new KeyGenerator() { 
         @Override 
         public Object generate(Object target, Method method, Object... 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(); 
         } 
        }; 
    } 
    
    }