2017-02-10 299 views
0

我有每天從db加載的所有客戶詳細信息的緩存。但是在加載每日客戶細節之前,我需要刪除緩存中的所有以前的條目。Java Guava Cache:如何清除所有緩存條目?

目前我做的:

public enum PeriodicUpdater { 

    TIMER; 
    private final AtomicBoolean isPublishing = new AtomicBoolean(false); 
    private final long   period  = TimeUnit.DAYS.toMillis(1); 

    @Autowired 
    @Qualifier("TestUtils") @Setter 
    private TestUtils testUtils; 

    public synchronized boolean initialize() { 
     return initialize(period, period); 
    } 


    boolean initialize(long delay, long period) { 
     if (isPublishing.get()) { 
      return false; 
     } 
     TimerTask task = new TimerTask() { 

      @Override public void run() { 
       try { 

        String path = getFile(); 
        if(TestUtils.getFileNameCache().getIfPresent(path) == null) { 
         TestUtils.setFileNameCache(testUtils.buildFileCache(path)); 
        } 
       } catch (Exception e) { 
        log.warn("Failed!", e); 
       } 
      } 
     }; 
     Timer timer = new Timer("PeriodicUpdater", true); // daemon=true 
     timer.schedule(task, delay, period); 
     isPublishing.set(true); 
     return true; 
    } 
} 

我在這裏使用了緩存:

public class TestUtils { 

     private static Cache<String, Map<String, List<String>>> fileCache = CacheBuilder 
       .newBuilder() 
       .expireAfterWrite(4, TimeUnit.DAYS) 
       .build(); 


    public TestUtils() { 

      String path = getFile(); 
      fileNameCache = buildFileCache(path); 
      } 

    public Cache<String, String> buildFileCache(String path) { 

      Cache<String, String> fileList = CacheBuilder 
        .newBuilder() 
        .expireAfterWrite(4, TimeUnit.DAYS) 
        .build(); 

      fileList.put(path, new Date().toString()); 

      return fileList; 
     } 
/* doing some stuff with the cache */ 

     } 

這是正確的做的?我看不到緩存被清除。如果我錯了,有人能糾正我嗎?

+1

'Cache'有一個方法' invalidateAll()'清除所有的條目,我沒有看到你調用它 – shmosel

+0

由於您使用的是谷歌庫,我將在[水平對齊](https://google.github.io/ styleguide/javaguide.html#s4.6.3-horizo​​ntal-alignment)谷歌的Java風格指南 – shmosel

+1

使用谷歌圖書館和採用谷歌編碼風格是不相干的(儘管我發現OP的水平對齊也有點令人不安):P) –

回答

0

Cache.invalidateAll()將清除當前緩存中的所有條目。這就是說,如果你打算每天重新加載條目,爲什麼你只會每四天到期緩存的內容? (.expireAfterWrite(4, TimeUnit.DAYS)只需改變41也將重新加載內容,每天一次。

,阿德里安深提到你濫用枚舉。public enum PeriodicUpdater幾乎應該是public class PeriodicUpdater