2017-06-20 71 views
0

我有一個類使用靜態緩存,該靜態緩存在類的所有實例之間共享。我希望能夠在運行時設置緩存超時。使用命令行參數初始化靜態緩存

提供一個具體的用例:我緩存從雲存儲中獲取的值。我想在開發環境中比在prod中更快地刷新值。部署代碼時,它會爲與該環境相對應的配置文件提供參數。此配置文件可以包含緩存刷新時間的值。

public class Pipeline { 
    private static final LoadingCache<BlobId, Definitions> CACHE = 
     CacheBuilder.newBuilder() 
        .refreshAfterWrite(VALUE, TimeUnit.MINUTES) // <-- how do I set VALUE from a config file? 
        .build(
       new CacheLoader<BlobId, Definitions>() { 
        public Definitions load(BlobId key) throws Exception { 
         return DefinitionsLoader.load(key); 
        } 
       }); 
... 
} 

回答

0

在運行時動態加載不同的配置,你可以使用一個的.properties文件。在下面的示例中,我將屬性文件加載到靜態塊中,但您也可以在初始化緩存的靜態方法中實現邏輯。在他們的聲明中初始化

https://docs.oracle.com/javase/tutorial/essential/environment/properties.html

private static final LoadingCache<BlobId, Definitions> CACHE; 
static { 
    Properties prop = new Properties(); 
    try { 
     prop.load(new FileInputStream("config.properties")); 
    } catch (IOException e) { 
     // handle exception 
    } 

    Long value = Long.parseLong(prop.getProperty("value", "5")); 
    CACHE = CacheBuilder.newBuilder() 
      .refreshAfterWrite(value, TimeUnit.MINUTES) 
      .build(new CacheLoader<Integer, Definitions>() { 
       public Definitions load(BlobId key) throws Exception { 
        return DefinitionsLoader.load(key); 
       } 
      }); 

} 
0

靜態字段,你想要做的不是設計來進行參數設置。

此外,您的緩存加載不靈活。
如果明天你改變了主意,或者你想使用它們中的多個,你不能。
最後,它也是不可測試的。

如果要爲緩存加載提供特定行爲,最自然的方法是更改​​包含該字段的類的API。

您可以提供一個Pipeline構造函數,其參數long delayInMnToRefresh,您可以使用此參數設置緩存的刷新時間。

public Pipeline(int delayInMnToRefresh){ 
     CacheBuilder.newBuilder() 
        .refreshAfterWrite(delayInMnToRefresh, TimeUnit.MINUTES) 
     .... 
} 

如果你使用Spring,你可以用一個@Autowired構造函數,在運行時使用定義的屬性時,Spring上下文加載:

@Autowired 
public Pipeline(@Value("${clould.cache.delayInMnToRefresh}") int delayInMnToRefresh){ 

     .... 
} 

隨着這種方式,例如在定義的屬性ENV:

clould.cache.delayInMnToRefresh = 5

而且在督促以這種方式定義,例如另一個屬性:

clould.cache.delayInMnToRefresh = 15

當然,你可以實現無春(春季啓動)這一要求,但你應該簡單地執行更多的鍋爐板任務(在調用此方法之前加載屬性文件並處理環境概念)。