2012-08-05 34 views
0

我在獨立環境中使用Spring3.1。在Spring中檢索緩存列表

我想緩存我的條目。 所以在3.1,我可以使用@Cacheable這樣:

@Cacheable("client") 
@Override 
public ClientDTO getClientByLogin(String login) throws FixException 
{ 
    ClientDTO client = null; 
    try 
    { 
     client = (ClientDTO) jdbcTemplate.queryForObject(GET_CLIENT_BY_LOGIN_STATEMENT, new Object[] 
     { login }, new ClientDTO()); 
    } 
    catch (EmptyResultDataAccessException e) 
    { 
     log.error("Client login not exist in database. login=" + login); 
    } 

    if (client == null) 
    { 
     throw new FixException("Return null from DB when executing getClientByLogin(), login=" + login); 
    } 
    return client; 
} 

現在我每次調用getClient一次先來看看在它的高速緩存respositry。

如果我想檢索緩存列表以迭代它。我怎麼做?

謝謝。

回答

-2

我找到了一個解決方案:

private ClientDTO getClientDTOByClientId(Integer clientId) 
{ 
    ClientDTO clientDTO = null; 
    Cache clientCache = null; 
    try 
    { 
     clientCache = ehCacheCacheManager.getCache("client"); 
     clientDTO = null; 
     if (clientCache != null) 
     { 
      clientDTO = (ClientDTO) clientCache.get(clientId); 
     } 
     else 
     { 
      log.error("clientCache is null"); 
     } 
    } 
    catch (Exception e) 
    { 
     log.error("Couldnt retrieve client from cache. clientId=" + clientId); 
    } 
    return clientDTO; 
} 
+1

你說你想獲得所有緩存對象的列表,但你在這裏只是獲取單個對象... – kaqqao 2015-09-06 21:01:37

2

在Spring Cache中沒有這樣的方法來迭代緩存列表。如果你想遍歷ClientDTO收集你需要把它放入緩存:

@Cacheable(value="client", key="all") 
@Override 
public List<ClientDTO> getAll() throws FixException { 
    List<ClientDTO> clients = null; 
    try { 
    clients = ....; // fetch all objects 
    } catch (EmptyResultDataAccessException e) { 
    // 
    } 

    if (clients == null) { 
    // 
    } 
    return clients; 
} 

在這種情況下,每次修改客戶端對象,你應該無效列表。

+0

檢查我的解決方案。你不覺得它做的工作? – rayman 2012-08-06 06:34:45

+0

它做了一些事情,但它沒有正確使用Spring Cache。 getClientDTOByClientId方法如何與getClientByLogin連接?它不會返回所有客戶端的列表,只有一個在緩存中。 – ragnor 2012-08-06 07:57:46

+0

我確實只想要緩存中的那些。 – rayman 2012-08-06 09:42:38

1

如果要檢索緩存的對象,然後將下面的代碼應該工作

public ClientDTO getCachedClient() { 
     Cache cache = cacheManager.getCache("client"); 
     Object cachedObject = null; 
     Object nativeCache = cache.getNativeCache(); 
     if (nativeCache instanceof net.sf.ehcache.Ehcache) { 
      net.sf.ehcache.Ehcache ehCache = (net.sf.ehcache.Ehcache) nativeCache; 
      List<Object> keys = ehCache.getKeys(); 

      if (keys.size() > 0) { 
       for (Object key : keys) { 
        Element element = ehCache.get(key); 
        if (element != null) { 

         cachedObject = element.getObjectValue(); 

        } 
       } 
      } 
     } 
     return (ClientDTO)cachedObject; 

    }