2015-12-02 2 views
0

Я настроил в mule object-store-cache-strategy, который работает с MongoDB.TTL кэша с использованием MongoDB в mule

<ee:object-store-caching-strategy name="MongoDB_Caching_Strategy" doc:name="Caching Strategy"> <spring-object-store ref="MongoDB_object_store" /> </ee:object-store-caching-strategy>

Используется с пружиной:

<spring:bean id="MongoDB_object_store" class="org.mule.module.mongo.MongoObjectStore" init-method="initialize" scope="singleton"> <spring:property name="host" value="localhost"/> <spring:property name="port" value="27017"/> <spring:property name="database" value="test"/> <spring:property name="username" value="test"/> <spring:property name="writeConcern" value="DATABASE_DEFAULT"/> </spring:bean>

Я хочу, чтобы настроить TTL для кэша.

Где я должен это делать?

EDIT:

Я добавил класс "ExpirableMongoObjectStore" -

public class ExpirableMongoObjectStore<T extends Serializable> extends MongoObjectStore { 

/** 
* The maxEntries of the Mongo cache 
*/ 
@Optional 
@DefaultValue("-1") 
private int maxEntries; 

/** 
* The maxEntries of the Mongo cache 
*/ 
@Optional 
@DefaultValue("600000") 
private int entryTTL; 

/** 
* The maxEntries of the Mongo cache 
*/ 
@Optional 
@DefaultValue("1000") 
private int expirationInterval; 

private MongoClient mongoClient; 
private static final String TIMESTAMP_FIELD = "timestamp"; 
protected final Log logger = LogFactory.getLog(this.getClass()); 

public void setEntryTTL(int entryTTL) {this.entryTTL = entryTTL; } 
public void setExpirationInterval(int expirationInterval) { this.expirationInterval = expirationInterval;} 
public void setMaxEntries(int maxEntries){this.maxEntries = maxEntries; } 
public int getEntryTTL(){ return entryTTL;} 
public int getExpirationInterval() {return expirationInterval;} 
public int getMaxEntries() { return maxEntries;} 

protected ConcurrentSkipListMap<Long, StoredObject<T>> store; 
public ExpirableMongoObjectStore() 
{ 

     this.store = new ConcurrentSkipListMap<Long, StoredObject<T>>(); 
     logger.debug("ddd"); 
} 

@Override 
public void expire(int entryTTL, int maxEntries) throws ObjectStoreException   
{ 
    //Option 1: 
     /*if ((entryTTL > 0)) 
     { 
      final long now = System.nanoTime(); 
      int expiredEntries = 0; 
      Map.Entry<?, ?> oldestEntry; 

      purge: 
      while ((oldestEntry = store.firstEntry()) != null) 
      { 
       Long oldestKey = (Long) oldestEntry.getKey(); 
       long oldestKeyValue = oldestKey.longValue(); 

       if (TimeUnit.NANOSECONDS.toMillis(now - oldestKeyValue) >= entryTTL) 
       { 
        store.remove(oldestKey); 
        expiredEntries++; 
       } 
       else 
       { 
        break purge; 
       } 
      } 

      if (logger.isDebugEnabled()) 
      { 
       logger.debug("Expired " + expiredEntries + " old entries"); 
      } 
     }*/ 

    //Option 2: 
     super.expire(getEntryTTL(), getMaxEntries()); 

    //Option 3: 
     /*final String partitionName = "OBJECTSTORE_DEFAULT_PARTITION_NAME"; 

     final String collection = getCollectionName(partitionName); 
     final long expireAt = System.currentTimeMillis() - entryTTL; 
     final DBObject query = QueryBuilder.start(TIMESTAMP_FIELD).lessThan(expireAt).get(); 
     mongoClient.removeObjects(collection, query, getWriteConcern());*/ 
} 

protected static class StoredObject<T> 
{ 
    private Serializable id; 
    private T item; 

    public StoredObject(Serializable id, T item) 
    { 
     this.id = id; 
     this.item = item; 
    } 

    public Serializable getId() 
    { 
     return id; 
    } 

    public T getItem() 
    { 
     return item; 
    } 

    @Override 
    @SuppressWarnings("unchecked") 
    public boolean equals(Object o) 
    { 
     if (this == o) 
     { 
      return true; 
     } 

     if (o == null || getClass() != o.getClass()) 
     { 
      return false; 
     } 

     StoredObject<T> that = (StoredObject<T>) o; 
     if (!id.equals(that.id)) 
     { 
      return false; 
     } 
     return true; 
    } 

    @Override 
    public int hashCode() 
    { 
     return id.hashCode(); 
    } 

    @Override 
    public String toString() 
    { 
     final StringBuilder sb = new StringBuilder(); 
     sb.append("StoredObject"); 
     sb.append("{id='").append(id).append('\''); 
     sb.append(", item=").append(item); 
     sb.append('}'); 
     return sb.toString(); 
    } 
} 

Есть 3 варианта метода 'истекает', как его реализовать. Я не знаю, что предпочитает. и с каждым из них кажется, что это не работает - срок действия не запущен. Кто-то знает почему? что проблема?

ответ

0

Довольно уверен, что это

<ee:object-store-caching-strategy name="MongoDB_Caching_Strategy" doc:name="Caching Strategy"> 
    <spring-object-store ref="MongoDB_object_store" entryTTL="200"/> 
</ee:object-store-caching-strategy> 

НТН

+0

Хотя я думаю, что это относится только к '' 'in-memory-object-store'''. – afelisatti

+0

спасибо, но его невозможно добавить. – user4593578

0

InMemoryObjectStore наследуется от http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/util/store/AbstractMonitoredObjectStore.html, который позволяет вам установить entryTTL.

Принимая во внимание, что MongoObjectStore нет.

Вы можете попробовать: MongoobjectStore и добавляете entryTTL пункт. Затем переопределите метод expire от org.mule.api.store.PartitionableExpirableObjectStore, который уже реализован MongoObjectStore. Вы можете попробовать использовать ту же логику из метода expire в классе InMemoryObjectStore: http://grepcode.com/file/repo1.maven.org/maven2/org.mule/mule-core/3.5.0/org/mule/util/store/InMemoryObjectStore.java#InMemoryObjectStore.expire%28%29

+0

спасибо, Если вы можете показать мне пример кода, что вы имеете в виду, это очень помогает мне. – user4593578

+0

или как я могу получить доступ к классу MongoobjectStore ... – user4593578

+0

I смысл - мне нужно сделать это в xml или создать класс? – user4593578

Смежные вопросы