Search in sources :

Example 61 with ContinuousQuery

use of org.apache.ignite.cache.query.ContinuousQuery in project ignite by apache.

the class CacheContinuousQueryExample method main.

/**
 * Executes example.
 *
 * @param args Command line arguments, none required.
 * @throws Exception If example execution failed.
 */
public static void main(String[] args) throws Exception {
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println();
        System.out.println(">>> Cache continuous query example started.");
        // Auto-close cache at the end of the example.
        try (IgniteCache<Integer, String> cache = ignite.getOrCreateCache(CACHE_NAME)) {
            int keyCnt = 20;
            // These entries will be queried by initial predicate.
            for (int i = 0; i < keyCnt; i++) cache.put(i, Integer.toString(i));
            // Create new continuous query.
            ContinuousQuery<Integer, String> qry = new ContinuousQuery<>();
            qry.setInitialQuery(new ScanQuery<>(new IgniteBiPredicate<Integer, String>() {

                @Override
                public boolean apply(Integer key, String val) {
                    return key > 10;
                }
            }));
            // Callback that is called locally when update notifications are received.
            qry.setLocalListener(new CacheEntryUpdatedListener<Integer, String>() {

                @Override
                public void onUpdated(Iterable<CacheEntryEvent<? extends Integer, ? extends String>> evts) {
                    for (CacheEntryEvent<? extends Integer, ? extends String> e : evts) System.out.println("Updated entry [key=" + e.getKey() + ", val=" + e.getValue() + ']');
                }
            });
            // This filter will be evaluated remotely on all nodes.
            // Entry that pass this filter will be sent to the caller.
            qry.setRemoteFilterFactory(new Factory<CacheEntryEventFilter<Integer, String>>() {

                @Override
                public CacheEntryEventFilter<Integer, String> create() {
                    return new CacheEntryEventFilter<Integer, String>() {

                        @Override
                        public boolean evaluate(CacheEntryEvent<? extends Integer, ? extends String> e) {
                            return e.getKey() > 10;
                        }
                    };
                }
            });
            // Execute query.
            try (QueryCursor<Cache.Entry<Integer, String>> cur = cache.query(qry)) {
                // Iterate through existing data.
                for (Cache.Entry<Integer, String> e : cur) System.out.println("Queried existing entry [key=" + e.getKey() + ", val=" + e.getValue() + ']');
                // Add a few more keys and watch more query notifications.
                for (int i = keyCnt; i < keyCnt + 10; i++) cache.put(i, Integer.toString(i));
                // Wait for a while while callback is notified about remaining puts.
                Thread.sleep(2000);
            }
        } finally {
            // Distributed cache could be removed from cluster only by #destroyCache() call.
            ignite.destroyCache(CACHE_NAME);
        }
    }
}
Also used : IgniteBiPredicate(org.apache.ignite.lang.IgniteBiPredicate) CacheEntryEventFilter(javax.cache.event.CacheEntryEventFilter) CacheEntryEvent(javax.cache.event.CacheEntryEvent) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) Ignite(org.apache.ignite.Ignite) IgniteCache(org.apache.ignite.IgniteCache) Cache(javax.cache.Cache)

Example 62 with ContinuousQuery

use of org.apache.ignite.cache.query.ContinuousQuery in project ignite by apache.

the class BinaryMetadataRegistrationInsideEntryProcessorTest method testContinuousQueryAndBinaryObjectBuilder.

/**
 * Continuously execute multiple EntryProcessors with having continuous queries in parallel.
 * This used to lead to several deadlocks.
 *
 * @throws Exception If failed.
 */
@Test
public void testContinuousQueryAndBinaryObjectBuilder() throws Exception {
    startGrids(3).cluster().active(true);
    grid(0).createCache(new CacheConfiguration<>().setName(CACHE_NAME).setAtomicityMode(ATOMIC).setBackups(2).setCacheMode(PARTITIONED).setWriteSynchronizationMode(FULL_SYNC).setPartitionLossPolicy(READ_WRITE_SAFE));
    IgniteEx client1 = startClientGrid(getConfiguration().setIgniteInstanceName("client1"));
    IgniteEx client2 = startClientGrid(getConfiguration().setIgniteInstanceName("client2"));
    AtomicBoolean stop = new AtomicBoolean();
    AtomicInteger keyCntr = new AtomicInteger();
    AtomicInteger binaryTypeCntr = new AtomicInteger();
    /**
     */
    class MyEntryProcessor implements CacheEntryProcessor<Object, Object, Object> {

        /**
         * Cached int value retrieved from {@code binaryTypeCntr} variable.
         */
        private int i;

        /**
         */
        public MyEntryProcessor(int i) {
            this.i = i;
        }

        /**
         */
        @IgniteInstanceResource
        Ignite ignite;

        /**
         * {@inheritDoc}
         */
        @Override
        public Object process(MutableEntry<Object, Object> entry, Object... arguments) throws EntryProcessorException {
            BinaryObjectBuilder builder = ignite.binary().builder("my_type");
            builder.setField("new_field" + i, i);
            entry.setValue(builder.build());
            return null;
        }
    }
    IgniteInternalFuture fut1 = GridTestUtils.runMultiThreadedAsync(() -> {
        IgniteCache<Object, Object> cache = client1.cache(CACHE_NAME).withKeepBinary();
        while (!stop.get()) {
            Integer key = keyCntr.getAndIncrement();
            cache.put(key, key);
            cache.invoke(key, new MyEntryProcessor(binaryTypeCntr.get()));
            binaryTypeCntr.incrementAndGet();
        }
    }, 8, "writer-thread");
    IgniteInternalFuture fut2 = GridTestUtils.runAsync(() -> {
        IgniteCache<Object, Object> cache = client2.cache(CACHE_NAME).withKeepBinary();
        while (!stop.get()) {
            ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
            qry.setInitialQuery(new ScanQuery<>((key, val) -> true));
            qry.setLocalListener(evts -> {
            });
            // noinspection EmptyTryBlock
            try (QueryCursor<Cache.Entry<Object, Object>> cursor = cache.query(qry)) {
            // No-op.
            }
        }
    });
    doSleep(10_000);
    stop.set(true);
    fut1.get(10, TimeUnit.SECONDS);
    fut2.get(10, TimeUnit.SECONDS);
}
Also used : IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) READ_WRITE_SAFE(org.apache.ignite.cache.PartitionLossPolicy.READ_WRITE_SAFE) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) IgniteEx(org.apache.ignite.internal.IgniteEx) EntryProcessorException(javax.cache.processor.EntryProcessorException) EntryProcessor(javax.cache.processor.EntryProcessor) MutableEntry(javax.cache.processor.MutableEntry) BinaryObjectBuilder(org.apache.ignite.binary.BinaryObjectBuilder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) After(org.junit.After) Cache(javax.cache.Cache) PARTITIONED(org.apache.ignite.cache.CacheMode.PARTITIONED) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) TcpDiscoveryVmIpFinder(org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder) IgniteInstanceResource(org.apache.ignite.resources.IgniteInstanceResource) Test(org.junit.Test) Ignite(org.apache.ignite.Ignite) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) FULL_SYNC(org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC) IgniteCache(org.apache.ignite.IgniteCache) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) TimeUnit(java.util.concurrent.TimeUnit) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) CacheEntryProcessor(org.apache.ignite.cache.CacheEntryProcessor) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) QueryCursor(org.apache.ignite.cache.query.QueryCursor) TcpDiscoverySpi(org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi) ATOMIC(org.apache.ignite.cache.CacheAtomicityMode.ATOMIC) Collections(java.util.Collections) ScanQuery(org.apache.ignite.cache.query.ScanQuery) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MutableEntry(javax.cache.processor.MutableEntry) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CacheEntryProcessor(org.apache.ignite.cache.CacheEntryProcessor) IgniteEx(org.apache.ignite.internal.IgniteEx) Ignite(org.apache.ignite.Ignite) MutableEntry(javax.cache.processor.MutableEntry) BinaryObjectBuilder(org.apache.ignite.binary.BinaryObjectBuilder) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 63 with ContinuousQuery

use of org.apache.ignite.cache.query.ContinuousQuery in project ignite by apache.

the class IgniteClientReconnectContinuousProcessorTest method testCacheContinuousQueryReconnectNewServer.

/**
 * @throws Exception If failed.
 */
@Test
public void testCacheContinuousQueryReconnectNewServer() throws Exception {
    Ignite client = grid(serverCount());
    assertTrue(client.cluster().localNode().isClient());
    IgniteCache<Object, Object> clientCache = client.getOrCreateCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME));
    CacheEventListener lsnr = new CacheEventListener();
    ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
    qry.setAutoUnsubscribe(true);
    qry.setLocalListener(lsnr);
    QueryCursor<?> cur = clientCache.query(qry);
    continuousQueryReconnect(client, clientCache, lsnr);
    // Check new server registers listener for reconnected client.
    try (Ignite newSrv = startGrid(serverCount() + 1)) {
        awaitPartitionMapExchange();
        lsnr.latch = new CountDownLatch(10);
        IgniteCache<Object, Object> newSrvCache = newSrv.cache(DEFAULT_CACHE_NAME);
        for (Integer key : primaryKeys(newSrvCache, 10)) newSrvCache.put(key, key);
        assertTrue(lsnr.latch.await(5000, MILLISECONDS));
    }
    cur.close();
    // Check new server does not register listener for closed query.
    try (Ignite newSrv = startGrid(serverCount() + 1)) {
        awaitPartitionMapExchange();
        lsnr.latch = new CountDownLatch(5);
        IgniteCache<Object, Object> newSrvCache = newSrv.cache(DEFAULT_CACHE_NAME);
        for (Integer key : primaryKeys(newSrvCache, 5)) newSrvCache.put(key, key);
        assertFalse(lsnr.latch.await(3000, MILLISECONDS));
    }
}
Also used : ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) Ignite(org.apache.ignite.Ignite) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 64 with ContinuousQuery

use of org.apache.ignite.cache.query.ContinuousQuery in project ignite by apache.

the class IgniteSlowClientDetectionSelfTest method testSlowClient.

/**
 * @throws Exception If failed.
 */
@Test
public void testSlowClient() throws Exception {
    final IgniteEx slowClient = grid(nodeCount() - 1);
    final ClusterNode slowClientNode = slowClient.localNode();
    final CountDownLatch evtSegmentedLatch = new CountDownLatch(1);
    slowClient.events().localListen(new IgnitePredicate<Event>() {

        @Override
        public boolean apply(Event evt) {
            assertEquals("Unexpected event: " + evt, evt.type(), EventType.EVT_NODE_SEGMENTED);
            DiscoveryEvent evt0 = (DiscoveryEvent) evt;
            assertEquals(slowClientNode, evt0.eventNode());
            assertEquals(5L, evt0.topologyVersion());
            evtSegmentedLatch.countDown();
            return false;
        }
    }, EventType.EVT_NODE_SEGMENTED);
    final CountDownLatch evtFailedLatch = new CountDownLatch(nodeCount() - 1);
    for (int i = 0; i < nodeCount() - 1; i++) {
        grid(i).events().localListen(new IgnitePredicate<Event>() {

            @Override
            public boolean apply(Event evt) {
                assertEquals("Unexpected event: " + evt, evt.type(), EventType.EVT_NODE_FAILED);
                DiscoveryEvent evt0 = (DiscoveryEvent) evt;
                assertEquals(slowClientNode, evt0.eventNode());
                assertEquals(6L, evt0.topologyVersion());
                assertEquals(4, evt0.topologyNodes().size());
                evtFailedLatch.countDown();
                return false;
            }
        }, EventType.EVT_NODE_FAILED);
    }
    assertTrue(slowClient.cluster().localNode().isClient());
    IgniteCache<Object, Object> cache = slowClient.getOrCreateCache(PARTITIONED);
    IgniteEx client0 = grid(nodeCount() - 2);
    assertTrue(client0.cluster().localNode().isClient());
    IgniteCache<Object, Object> cache0 = client0.getOrCreateCache(PARTITIONED);
    cache.query(new ContinuousQuery<>().setLocalListener(new Listener()));
    for (int i = 0; i < 100; i++) cache0.put(0, i);
    GridIoManager ioMgr = slowClient.context().io();
    TcpCommunicationSpi commSpi = (TcpCommunicationSpi) ((Object[]) U.field(ioMgr, "spis"))[0];
    GridNioServer nioSrvr = ((GridNioServerWrapper) GridTestUtils.getFieldValue(commSpi, "nioSrvWrapper")).nio();
    GridTestUtils.setFieldValue(nioSrvr, "skipRead", true);
    // Initiate messages for client.
    for (int i = 0; i < 100; i++) cache0.put(0, new byte[10 * 1024]);
    boolean wait = GridTestUtils.waitForCondition(new GridAbsPredicate() {

        @Override
        public boolean apply() {
            return Ignition.state(slowClient.name()) == IgniteState.STOPPED_ON_SEGMENTATION;
        }
    }, getTestTimeout());
    assertTrue(wait);
    assertTrue("Failed to wait for client failed event", evtFailedLatch.await(5000, MILLISECONDS));
    assertTrue("Failed to wait for client segmented event", evtSegmentedLatch.await(5000, MILLISECONDS));
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) CacheEntryUpdatedListener(javax.cache.event.CacheEntryUpdatedListener) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) GridNioServerWrapper(org.apache.ignite.spi.communication.tcp.internal.GridNioServerWrapper) CountDownLatch(java.util.concurrent.CountDownLatch) TcpCommunicationSpi(org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi) GridNioServer(org.apache.ignite.internal.util.nio.GridNioServer) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) GridIoManager(org.apache.ignite.internal.managers.communication.GridIoManager) DiscoveryEvent(org.apache.ignite.events.DiscoveryEvent) Event(org.apache.ignite.events.Event) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Example 65 with ContinuousQuery

use of org.apache.ignite.cache.query.ContinuousQuery in project ignite by apache.

the class CacheEntryListenersTest method testListenersWithRemoteFilter.

/**
 * Test continuous queries and JCache entry listeners with remote filters.
 */
@Test
@SuppressWarnings("deprecation")
public void testListenersWithRemoteFilter() throws Exception {
    try (IgniteClient client = startClient(0, 1, 2)) {
        ClientCache<Integer, Integer> cache = client.getOrCreateCache("testListenersWithRmtFilter");
        CacheEntryEventSerializableFilter<Integer, Integer> rmtFilter = evt -> (evt.getKey() & 1) == 0;
        ContinuousQueryListener<Integer, Integer> lsnr1 = new ContinuousQueryListener<>();
        ContinuousQueryListener<Integer, Integer> lsnr2 = new ContinuousQueryListener<>();
        cache.query(new ContinuousQuery<Integer, Integer>().setLocalListener(lsnr1).setRemoteFilterFactory(() -> rmtFilter));
        cache.query(new ContinuousQuery<Integer, Integer>().setLocalListener(lsnr2).setRemoteFilter(rmtFilter));
        JCacheEntryListener<Integer, Integer> lsnr3 = new JCacheEntryListener<>();
        cache.registerCacheEntryListener(new MutableCacheEntryListenerConfiguration<>(() -> lsnr3, () -> rmtFilter, true, false));
        for (int i = 0; i < 10; i++) cache.put(i, i);
        Map<EventType, Map<Integer, Integer>> expRes = F.asMap(EventType.CREATED, IntStream.range(0, 5).boxed().collect(Collectors.toMap(i -> i * 2, i -> i * 2)));
        assertEquals(expRes, aggregateListenerEvents(lsnr1, 5));
        assertEquals(expRes, aggregateListenerEvents(lsnr2, 5));
        assertEquals(expRes, aggregateListenerEvents(lsnr3, 5));
        for (int i = 0; i < 10; i++) cache.put(i, -i);
        expRes = F.asMap(EventType.UPDATED, IntStream.range(0, 5).boxed().collect(Collectors.toMap(i -> i * 2, i -> -i * 2)));
        assertEquals(expRes, aggregateListenerEvents(lsnr1, 5));
        assertEquals(expRes, aggregateListenerEvents(lsnr2, 5));
        assertEquals(expRes, aggregateListenerEvents(lsnr3, 5));
        for (int i = 0; i < 10; i++) cache.remove(i);
        expRes = F.asMap(EventType.REMOVED, IntStream.range(0, 5).boxed().collect(Collectors.toMap(i -> i * 2, i -> -i * 2)));
        assertEquals(expRes, aggregateListenerEvents(lsnr1, 5));
        assertEquals(expRes, aggregateListenerEvents(lsnr2, 5));
        assertEquals(expRes, aggregateListenerEvents(lsnr3, 5));
        assertTrue(lsnr1.isQueueEmpty());
        assertTrue(lsnr2.isQueueEmpty());
        assertTrue(lsnr3.isQueueEmpty());
    }
}
Also used : IntStream(java.util.stream.IntStream) ClientDisconnectListener(org.apache.ignite.client.ClientDisconnectListener) Person(org.apache.ignite.client.Person) GridTestUtils.waitForCondition(org.apache.ignite.testframework.GridTestUtils.waitForCondition) CacheEntryEventSerializableFilter(org.apache.ignite.cache.CacheEntryEventSerializableFilter) U(org.apache.ignite.internal.util.typedef.internal.U) HashMap(java.util.HashMap) CacheEntryExpiredListener(javax.cache.event.CacheEntryExpiredListener) ClientCache(org.apache.ignite.client.ClientCache) HashSet(java.util.HashSet) Future(java.util.concurrent.Future) CacheEntryListenerConfiguration(javax.cache.configuration.CacheEntryListenerConfiguration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgniteClient(org.apache.ignite.client.IgniteClient) Map(java.util.Map) Cache(javax.cache.Cache) CacheEntryCreatedListener(javax.cache.event.CacheEntryCreatedListener) CacheEntryUpdatedListener(javax.cache.event.CacheEntryUpdatedListener) Duration(javax.cache.expiry.Duration) MutableCacheEntryListenerConfiguration(javax.cache.configuration.MutableCacheEntryListenerConfiguration) F(org.apache.ignite.internal.util.typedef.F) EventType(javax.cache.event.EventType) CreatedExpiryPolicy(javax.cache.expiry.CreatedExpiryPolicy) GridTestUtils.assertThrowsWithCause(org.apache.ignite.testframework.GridTestUtils.assertThrowsWithCause) EnumMap(java.util.EnumMap) FactoryBuilder(javax.cache.configuration.FactoryBuilder) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) Test(org.junit.Test) UUID(java.util.UUID) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) IgniteCache(org.apache.ignite.IgniteCache) T2(org.apache.ignite.internal.util.typedef.T2) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) TimeUnit(java.util.concurrent.TimeUnit) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) CacheEntryEvent(javax.cache.event.CacheEntryEvent) CacheEntryRemovedListener(javax.cache.event.CacheEntryRemovedListener) ThinClientConfiguration(org.apache.ignite.configuration.ThinClientConfiguration) QueryCursor(org.apache.ignite.cache.query.QueryCursor) ScanQuery(org.apache.ignite.cache.query.ScanQuery) ClientConnectorConfiguration(org.apache.ignite.configuration.ClientConnectorConfiguration) EventType(javax.cache.event.EventType) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgniteClient(org.apache.ignite.client.IgniteClient) HashMap(java.util.HashMap) Map(java.util.Map) EnumMap(java.util.EnumMap) Test(org.junit.Test)

Aggregations

ContinuousQuery (org.apache.ignite.cache.query.ContinuousQuery)123 Test (org.junit.Test)74 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)70 Ignite (org.apache.ignite.Ignite)60 CacheEntryEvent (javax.cache.event.CacheEntryEvent)58 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)53 CountDownLatch (java.util.concurrent.CountDownLatch)48 IgniteCache (org.apache.ignite.IgniteCache)43 QueryCursor (org.apache.ignite.cache.query.QueryCursor)38 ArrayList (java.util.ArrayList)32 IgniteException (org.apache.ignite.IgniteException)28 CacheEntryListenerException (javax.cache.event.CacheEntryListenerException)27 CacheEntryUpdatedListener (javax.cache.event.CacheEntryUpdatedListener)24 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)22 Cache (javax.cache.Cache)22 HashMap (java.util.HashMap)21 List (java.util.List)19 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)19 CacheException (javax.cache.CacheException)17 IgniteEx (org.apache.ignite.internal.IgniteEx)17