2017-02-10 8 views
0

私はすべての顧客の詳細がdbから毎日読み込まれるキャッシュを持っています。しかし、毎日の顧客の詳細を読み込む前に、私はキャッシュ内のすべての前のエントリを削除する必要があります。Java Guavaキャッシュ:すべてのキャッシュエントリをクリアするには?

現在、私はやっている:

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'には'メソッドを持っています – shmosel

+0

Googleライブラリーを使用しているので、このメモを[横書き](https://google.github.io/)にドロップします。 – shmosel

+1

googleのライブラリを使用してGoogleのコーディングスタイルを採用することは無関係です(ただし、私はOPの水平方向の位置合わせにも邪魔をしていましたが、P) –

答えて

0

Cache.invalidateAll()は、現在キャッシュにあるすべてのエントリをクリアします。

つまり、エントリを毎日リロードする予定の場合、4日ごとにキャッシュの内容が期限切れになるのはなぜですか? (.expireAfterWrite(4, TimeUnit.DAYS)が。単に14を変更すると、一日一回の内容をリロードします。

をまた、エイドリアン・シャムはあなたが列挙型を悪用している述べたように。public enum PeriodicUpdaterはほぼ確実public class PeriodicUpdaterでなければなりません。

関連する問題