Java Code Examples for org.apache.ignite.IgniteCache#withExpiryPolicy()

The following examples show how to use org.apache.ignite.IgniteCache#withExpiryPolicy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GridCacheOffheapIndexGetSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testWithExpiryPolicy() throws Exception {
    IgniteCache<Long, Long> cache = jcache(grid(0), cacheConfiguration(), Long.class, Long.class);

    cache = cache.withExpiryPolicy(new TestExiryPolicy());

    for (long i = 0; i < 100; i++)
        cache.put(i, i);

    for (long i = 0; i < 100; i++)
        assertEquals((Long)i, cache.get(i));

    SqlQuery<Long, Long> qry = new SqlQuery<>(Long.class, "_val >= 90");

    List<Cache.Entry<Long, Long>> res = cache.query(qry).getAll();

    assertEquals(10, res.size());

    for (Cache.Entry<Long, Long> e : res) {
        assertNotNull(e.getKey());
        assertNotNull(e.getValue());
    }
}
 
Example 2
Source File: WebSessionFilter.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param maxInactiveInteval Interval to use in expiry policy.
 * @param cache Cache.
 * @param <T> Cached object type.
 * @return Cache with expiry policy if {@code maxInactiveInteval} greater than zero.
 */
private <T> IgniteCache<String, T> cacheWithExpiryPolicy(final int maxInactiveInteval,
    final IgniteCache<String, T> cache) {
    if (maxInactiveInteval > 0) {
        long ttl = maxInactiveInteval * 1000L;

        ExpiryPolicy plc = new ModifiedExpiryPolicy(new Duration(MILLISECONDS, ttl));

        return cache.withExpiryPolicy(plc);
    }

    return cache;
}
 
Example 3
Source File: CacheQueryFilterExpiredTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param ignite Node.
 * @param atomicityMode Cache atomicity mode.
 * @param eagerTtl Value for {@link CacheConfiguration#setEagerTtl(boolean)}.
 * @throws Exception If failed.
 */
private void checkFilterExpired(Ignite ignite, CacheAtomicityMode atomicityMode, boolean eagerTtl) throws Exception {
    CacheConfiguration<Integer, Integer> ccfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME);
    ccfg.setAtomicityMode(atomicityMode);
    ccfg.setEagerTtl(eagerTtl);
    ccfg.setIndexedTypes(Integer.class, Integer.class);

    final IgniteCache<Integer, Integer> cache = ignite.createCache(ccfg);

    try {
        IgniteCache<Integer, Integer> expCache =
            cache.withExpiryPolicy(new TouchedExpiryPolicy(new Duration(0, 2000)));

        for (int i = 0; i < 10; i++) {
            IgniteCache<Integer, Integer> cache0 = i % 2 == 0 ? cache : expCache;

            cache0.put(i, i);
        }

        assertEquals(10, cache.query(new SqlQuery<Integer, Integer>(Integer.class, "1=1")).getAll().size());
        assertEquals(10, cache.query(new SqlFieldsQuery("select _key, _val from Integer")).getAll().size());

        GridTestUtils.waitForCondition(new GridAbsPredicate() {
            @Override public boolean apply() {
                return cache.query(new SqlQuery<Integer, Integer>(Integer.class, "1=1")).getAll().size() == 5 &&
                    cache.query(new SqlFieldsQuery("select _key, _val from Integer")).getAll().size() == 5;
            }
        }, 5000);

        assertEquals(5, cache.query(new SqlQuery<Integer, Integer>(Integer.class, "1=1")).getAll().size());
        assertEquals(5, cache.query(new SqlFieldsQuery("select _key, _val from Integer")).getAll().size());
    }
    finally {
        ignite.destroyCache(ccfg.getName());
    }
}
 
Example 4
Source File: H2RowExpireTimeIndexSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Put values into the table with expire policy. Inserted row become expired in {@link #EXPIRE_IN_MS_FROM_CREATE}
 * milliseconds.
 *
 * @param cache cache to put values in.
 * @param key key of the row.
 * @param val value of the row.
 */
private void putExpiredSoon(IgniteCache cache, Integer key, Integer val) {
    CreatedExpiryPolicy expireSinceCreated = new CreatedExpiryPolicy(new Duration(TimeUnit.MILLISECONDS,
        EXPIRE_IN_MS_FROM_CREATE));

    IgniteCache<Integer, Integer> expCache = cache.withExpiryPolicy(expireSinceCreated);

    expCache.put(key, val);
}
 
Example 5
Source File: H2RowExpireTimeIndexSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Put values into the table with expire policy.
 *
 * @param cache cache to put values in.
 * @param key key of the row.
 * @param val value of the row.
 */
private void putExpireInYear(IgniteCache cache, Integer key, Integer val) {
    CreatedExpiryPolicy expireSinceCreated = new CreatedExpiryPolicy(new Duration(TimeUnit.MILLISECONDS,
        TimeUnit.DAYS.toMillis(365)));

    IgniteCache<Integer, Integer> expCache = cache.withExpiryPolicy(expireSinceCreated);

    expCache.put(key, val);
}
 
Example 6
Source File: ClientCacheRequest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the cache for current cache id, ignoring any flags.
 *
 * @param ctx Kernal context.
 * @return Cache.
 */
protected IgniteCache rawCache(ClientConnectionContext ctx) {
    DynamicCacheDescriptor cacheDesc = cacheDescriptor(ctx);

    String cacheName = cacheDesc.cacheName();

    IgniteCache<Object, Object> cache = ctx.kernalContext().grid().cache(cacheName);
    if (withExpiryPolicy())
        cache = cache.withExpiryPolicy(expiryPolicy);
    
    return cache;
}
 
Example 7
Source File: CacheMvccTransactionsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Ignore("https://issues.apache.org/jira/browse/IGNITE-7311")
@Test
public void testChangeExpireTime() throws Exception {
    final IgniteEx node = startGrid(0);

    IgniteCache cache = node.createCache(cacheConfiguration(PARTITIONED, FULL_SYNC, 1, 64));

    cache.put(1, 1);

    final IgniteCache expiryCache =
        cache.withExpiryPolicy(new TouchedExpiryPolicy(new Duration(TimeUnit.SECONDS, 1)));

    expiryCache.get(1);
}
 
Example 8
Source File: IgniteCacheEntryListenerExpiredEventsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param ccfg Cache configuration.
 * @throws Exception If failed.
 */
private void checkExpiredEvents(CacheConfiguration<Object, Object> ccfg) throws Exception {
    IgniteCache<Object, Object> cache = ignite(0).createCache(ccfg);

    try {
        evtCntr = new AtomicInteger();

        CacheEntryListenerConfiguration<Object, Object> lsnrCfg = new MutableCacheEntryListenerConfiguration<>(
            new ExpiredListenerFactory(),
            null,
            true,
            false
        );

        cache.registerCacheEntryListener(lsnrCfg);

        IgniteCache<Object, Object> expiryCache =
            cache.withExpiryPolicy(new ModifiedExpiryPolicy(new Duration(MILLISECONDS, 500)));

        expiryCache.put(1, 1);

        for (int i = 0; i < 10; i++)
            cache.get(i);

        boolean wait = GridTestUtils.waitForCondition(new GridAbsPredicate() {
            @Override public boolean apply() {
                return evtCntr.get() > 0;
            }
        }, 5000);

        assertTrue(wait);

        U.sleep(100);

        assertEquals(1, evtCntr.get());
    }
    finally {
        ignite(0).destroyCache(cache.getName());
    }
}
 
Example 9
Source File: CacheContinuousWithTransformerReplicatedSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testExpired() throws Exception {
    Ignite ignite = gridToRunQuery();

    IgniteCache<Integer, Employee> cache = ignite.cache(DEFAULT_CACHE_NAME);

    cache = cache.withExpiryPolicy(new CreatedExpiryPolicy(new Duration(MILLISECONDS, 100)));

    final Set<Integer> keys = new GridConcurrentHashSet<>();
    final CountDownLatch latch = new CountDownLatch(2);

    ContinuousQueryWithTransformer<Integer, Employee, Integer> qry = new ContinuousQueryWithTransformer<>();

    qry.setIncludeExpired(true);

    qry.setRemoteFilterFactory(FactoryBuilder.factoryOf(new CacheEntryEventSerializableFilter<Integer, Employee>() {
        @Override public boolean evaluate(CacheEntryEvent event) throws CacheEntryListenerException {
            return event.getEventType() == EventType.EXPIRED;
        }
    }));

    qry.setRemoteTransformerFactory(FactoryBuilder.factoryOf(
        new IgniteClosure<CacheEntryEvent<? extends Integer, ? extends Employee>, Integer>() {
            @Override public Integer apply(CacheEntryEvent<? extends Integer, ? extends Employee> evt) {
                assertNotNull(evt.getValue());

                assertNotNull(evt.getOldValue());

                return evt.getKey();
            }
        }));

    qry.setLocalListener(new EventListener<Integer>() {
        @Override public void onUpdated(Iterable<? extends Integer> evts) {
            for (Integer key : evts) {
                keys.add(key);

                latch.countDown();
            }
        }
    });

    try (QueryCursor<Cache.Entry<Integer, Employee>> ignored = cache.query(qry)) {
        cache.put(1, new Employee(SARAH_CONNOR, 42));
        cache.put(2, new Employee(JOHN_CONNOR, 42));

        // Wait for expiration.
        latch.await(LATCH_TIMEOUT, MILLISECONDS);

        assertEquals(2, keys.size());

        assertTrue(keys.contains(1));
        assertTrue(keys.contains(2));
    }
}
 
Example 10
Source File: CacheMvccTransactionsTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Ignore("https://issues.apache.org/jira/browse/IGNITE-7311")
@Test
public void testExpiration() throws Exception {
    final IgniteEx node = startGrid(0);

    IgniteCache cache = node.createCache(cacheConfiguration(PARTITIONED, FULL_SYNC, 1, 64));

    final IgniteCache expiryCache =
        cache.withExpiryPolicy(new TouchedExpiryPolicy(new Duration(TimeUnit.SECONDS, 1)));

    for (int i = 0; i < 10; i++)
        expiryCache.put(1, i);

    assertTrue("Failed to wait for expiration", GridTestUtils.waitForCondition(new GridAbsPredicate() {
        @Override public boolean apply() {
            return expiryCache.localPeek(1) == null;
        }
    }, 5000));

    for (int i = 0; i < 11; i++) {
        if (i % 2 == 0)
            expiryCache.put(1, i);
        else
            expiryCache.remove(1);
    }

    assertTrue("Failed to wait for expiration", GridTestUtils.waitForCondition(new GridAbsPredicate() {
        @Override public boolean apply() {
            return expiryCache.localPeek(1) == null;
        }
    }, 5000));

    expiryCache.put(1, 1);

    assertTrue("Failed to wait for expiration", GridTestUtils.waitForCondition(new GridAbsPredicate() {
        @Override public boolean apply() {
            try {
                GridCacheContext cctx = node.context().cache().context().cacheContext(CU.cacheId(DEFAULT_CACHE_NAME));

                KeyCacheObject key = cctx.toCacheKeyObject(1);

                return cctx.offheap().read(cctx, key) == null;
            }
            catch (Exception e) {
                fail();

                return false;
            }
        }
    }, 5000));
}
 
Example 11
Source File: IgniteCacheNoSyncForGetTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public Object call() throws Exception {
    IgniteCache cache = ignite.cache(cacheName);

    if (withExpiryPlc)
        cache = cache.withExpiryPolicy(ModifiedExpiryPolicy.factoryOf(Duration.FIVE_MINUTES).create());

    Map vals = cache.getAll(keys);

    Collection<CacheEntry> entries = cache.getEntries(keys);

    assertEquals(vals.size(), entries.size());

    for (CacheEntry entry : entries) {
        Object val = vals.get(entry.getKey());

        assertEquals(val, entry.getValue());
    }

    return vals;
}
 
Example 12
Source File: IgniteCacheExpiryPolicyAbstractTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * @throws Exception if failed.
 */
@Test
public void testCreateUpdate0() throws Exception {
    startGrids(1);

    long ttl = 60L;

    final String key = "key1";

    final IgniteCache<String, String> cache = jcache();

    for (int i = 0; i < 1000; i++) {
        final IgniteCache<String, String> cache0 = cache.withExpiryPolicy(new ModifiedExpiryPolicy(new Duration(TimeUnit.HOURS, ttl)));

        cache0.put(key, key);

        info("PUT DONE");
    }

    long pSize = grid(0).context().cache().internalCache(DEFAULT_CACHE_NAME).context().ttl().pendingSize();

    assertTrue("Too many pending entries: " + pSize, pSize <= 1);

    cache.remove(key);

    pSize = grid(0).context().cache().internalCache(DEFAULT_CACHE_NAME).context().ttl().pendingSize();

    assertEquals(0, pSize);
}
 
Example 13
Source File: IgniteCacheNoSyncForGetTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/** {@inheritDoc} */
@Override public Object call() throws Exception {
    IgniteCache cache = ignite.cache(cacheName);

    if (withExpiryPlc)
        cache = cache.withExpiryPolicy(ModifiedExpiryPolicy.factoryOf(Duration.FIVE_MINUTES).create());

    Object val = cache.get(key);

    CacheEntry e = cache.getEntry(key);

    assertEquals(val, e.getValue());

    return val;
}