2016-09-28 55 views
0

我目前正在一些運行在關係數據庫(PostgreSQL)和圖形一(Neo4j)上的算法運行比較實驗。 我實現了我的算法,作爲Neo4j的用戶定義過程,但它看起來不像它開箱即用執行任何緩存。 有沒有辦法在Neo4j中爲用戶定義的過程配置緩存?爲Neo4j用戶定義的過程緩存

感謝

回答

0

你必須自己實現緩存,如果是相關的使用情況和你有什麼要緩存:可能是一些不相關的交易,所以沒有節點或關係; Neo4j的ID很棘手,因爲它們可以被重用,所以最好只緩存它們,或者根本不緩存它們。應用程序級別的ID將會很好,就像由字符串或標量類型組成的bean一樣。

假設你有定義了這個過程:

public class MyProcedure { 
    @Context 
    public GraphDatabaseService db; 

    @Procedure 
    public Stream<MyBean> doSomething(@Name("uuid") String uuid) { 
     int count = 0; 
     // ... 
     return Stream.of(new MyBean(count)); 
    } 

    public static class MyBean { 
     public int count; 

     public MyBean(int count) { 
      this.count = count; 
     } 
    } 
} 

您可以使用ConcurrentMap添加一些簡單的緩存:

public class MyProcedure { 
    private static final ConcurrentMap<String, Collection<MyBean>> CACHE = 
      new ConcurrentHashMap<>(); 

    @Context 
    public GraphDatabaseService db; 

    @Procedure 
    public Stream<MyBean> doSomething(@Name("uuid") String uuid) { 
     Collection<MyBean> result = CACHE.computeIfAbsent(uuid, 
       k -> doSomethingCacheable(k).collect(Collectors.toList())); 
     return result.stream(); 
    } 

    private Stream<MyBean> doSomethingCacheable(String uuid) { 
     int count = 0; 
     // ... 
     return Stream.of(new MyBean(count)); 
    } 

    public static class MyBean { 
     // ... 
    } 
} 

請注意,您不能緩存Stream因爲它只能被消耗一次,所以你必須通過收集到一個ArrayList(你也可以在該方法內移動collect,將返回類型改爲Collection<MyBean>並使用方法引用)來自己使用它。如果該過程需要多個參數,則需要爲組合鍵創建合適的類(如果可能,請使用不變的正確的equals和實現)。 適用於可緩存值的限制也適用於密鑰。

這是一個永恆的,無界的緩存。如果您需要更多功能(過期,最大大小),我建議您使用真實緩存實施,如GuavaCache(或LoadingCache)或Ben Manes的Caffeine

+0

謝謝,我希望有一些開箱即用的東西,所以我可以比較緩存實現,但會嘗試一個你建議的庫而不是我自己創建的轉儲庫。 –