2017-08-17 116 views

回答

1

您可以使用Redis來達到此目的。

Redis是一個可用作緩存的開源內存數據結構存儲。它提供了一種將過期時間添加到密鑰的方法。到期後,密鑰將自動失效/從Redis中刪除。

在你的Maven,請提供以下依賴性:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-data-redis</artifactId> 
</dependency> 

在你SpringBoot的應用程序,你需要定義只是以下屬性:

spring.redis.host= 
spring.redis.port= 

,你可以設置過期時間,如:

public void put(final T key, final T hashKey, final Object value, final long exiryInMilliseconds) { 
     hashOps.put(key, hashKey, value); 
     if (exiryInMilliseconds > 0) { 
      redisTemplate.expire(key, exiryInMilliseconds, TimeUnit.MILLISECONDS); 
     } 

    } 

Both RedisTemplate & HashOperations是p由Redis核心軟件包提供。你可以像使用Spring一樣注入它們,或者通過自己創建實例來使用它們。

@Resource 
private RedisTemplate<T, T> redisTemplate; 

@Resource(name = "redisTemplate") 
private <T, T, Object> hashOps; 

在檢索的時候,如果你這樣做:

hashOps.get(key, hashKey); 

它將返回如果到期時間已過/或鍵不存在。否則你會得到你的對象。

+0

謝謝,我會試試 – yongguangl

+0

@yongguangl它對你有用嗎? – theLearner

+0

抱歉沒及時回覆,在此期間我忙於其他事項。當我添加依賴關係「spring-boot-starter-data-redis」時,出現了一個問題。 「redis jar」已下載,但無法正常工作。請查看我的更新。 – yongguangl