Search in sources :

Example 1 with ContinuousQuery

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

the class CacheContinuousQueryConcurrentPartitionUpdateTest method concurrentUpdatesAndQueryStart.

/**
     * @param atomicityMode Cache atomicity mode.
     * @throws Exception If failed.
     */
private void concurrentUpdatesAndQueryStart(CacheAtomicityMode atomicityMode) throws Exception {
    Ignite srv = startGrid(0);
    client = true;
    Ignite client = startGrid(1);
    CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
    ccfg.setWriteSynchronizationMode(FULL_SYNC);
    ccfg.setAtomicityMode(atomicityMode);
    IgniteCache clientCache = client.createCache(ccfg);
    Affinity<Integer> aff = srv.affinity(DEFAULT_CACHE_NAME);
    final List<Integer> keys = new ArrayList<>();
    final int KEYS = 10;
    for (int i = 0; i < 100_000; i++) {
        if (aff.partition(i) == 0) {
            keys.add(i);
            if (keys.size() == KEYS)
                break;
        }
    }
    assertEquals(KEYS, keys.size());
    final int THREADS = 10;
    final int UPDATES = 1000;
    for (int i = 0; i < 5; i++) {
        log.info("Iteration: " + i);
        ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
        final AtomicInteger evtCnt = new AtomicInteger();
        qry.setLocalListener(new CacheEntryUpdatedListener<Object, Object>() {

            @Override
            public void onUpdated(Iterable<CacheEntryEvent<?, ?>> evts) {
                for (CacheEntryEvent evt : evts) {
                    assertNotNull(evt.getKey());
                    assertNotNull(evt.getValue());
                    if ((Integer) evt.getValue() >= 0)
                        evtCnt.incrementAndGet();
                }
            }
        });
        QueryCursor cur;
        final IgniteCache<Object, Object> srvCache = srv.cache(DEFAULT_CACHE_NAME);
        final AtomicBoolean stop = new AtomicBoolean();
        try {
            IgniteInternalFuture fut = GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    ThreadLocalRandom rnd = ThreadLocalRandom.current();
                    while (!stop.get()) srvCache.put(keys.get(rnd.nextInt(KEYS)), rnd.nextInt(100) - 200);
                    return null;
                }
            }, THREADS, "update");
            U.sleep(1000);
            cur = clientCache.query(qry);
            U.sleep(1000);
            stop.set(true);
            fut.get();
        } finally {
            stop.set(true);
        }
        GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                ThreadLocalRandom rnd = ThreadLocalRandom.current();
                for (int i = 0; i < UPDATES; i++) srvCache.put(keys.get(rnd.nextInt(KEYS)), i);
                return null;
            }
        }, THREADS, "update");
        GridTestUtils.waitForCondition(new GridAbsPredicate() {

            @Override
            public boolean apply() {
                log.info("Events: " + evtCnt.get());
                return evtCnt.get() >= THREADS * UPDATES;
            }
        }, 5000);
        assertEquals(THREADS * UPDATES, evtCnt.get());
        cur.close();
    }
}
Also used : ArrayList(java.util.ArrayList) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) CacheEntryEvent(javax.cache.event.CacheEntryEvent) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Ignite(org.apache.ignite.Ignite) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) QueryCursor(org.apache.ignite.cache.query.QueryCursor) GridAbsPredicate(org.apache.ignite.internal.util.lang.GridAbsPredicate) IgniteCache(org.apache.ignite.IgniteCache) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 2 with ContinuousQuery

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

the class CacheContinuousQueryOperationP2PTest method testContinuousQuery.

/**
 * @param ccfg Cache configuration.
 * @param isClient Client.
 * @throws Exception If failed.
 */
protected void testContinuousQuery(CacheConfiguration<Object, Object> ccfg, boolean isClient) throws Exception {
    ignite(0).createCache(ccfg);
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    QueryCursor<?> cur = null;
    final Class<Factory<CacheEntryEventFilter>> evtFilterFactory = (Class<Factory<CacheEntryEventFilter>>) getExternalClassLoader().loadClass("org.apache.ignite.tests.p2p.CacheDeploymentEntryEventFilterFactory");
    final CountDownLatch latch = new CountDownLatch(10);
    ContinuousQuery<Integer, Integer> qry = new ContinuousQuery<>();
    TestLocalListener localLsnr = new TestLocalListener() {

        @Override
        public void onEvent(Iterable<CacheEntryEvent<? extends Integer, ? extends Integer>> evts) throws CacheEntryListenerException {
            for (CacheEntryEvent<? extends Integer, ? extends Integer> evt : evts) {
                latch.countDown();
                log.info("Received event: " + evt);
            }
        }
    };
    MutableCacheEntryListenerConfiguration<Integer, Integer> lsnrCfg = new MutableCacheEntryListenerConfiguration<>(new FactoryBuilder.SingletonFactory<>(localLsnr), (Factory<? extends CacheEntryEventFilter<? super Integer, ? super Integer>>) (Object) evtFilterFactory.newInstance(), true, true);
    qry.setLocalListener(localLsnr);
    qry.setRemoteFilterFactory((Factory<? extends CacheEntryEventFilter<Integer, Integer>>) (Object) evtFilterFactory.newInstance());
    IgniteCache<Integer, Integer> cache = null;
    try {
        if (isClient)
            cache = grid(NODES - 1).cache(ccfg.getName());
        else
            cache = grid(rnd.nextInt(NODES - 1)).cache(ccfg.getName());
        cur = cache.query(qry);
        cache.registerCacheEntryListener(lsnrCfg);
        for (int i = 0; i < 10; i++) cache.put(i, i);
        assertTrue(latch.await(3, TimeUnit.SECONDS));
    } finally {
        if (cur != null)
            cur.close();
        if (cache != null)
            cache.deregisterCacheEntryListener(lsnrCfg);
    }
}
Also used : MutableCacheEntryListenerConfiguration(javax.cache.configuration.MutableCacheEntryListenerConfiguration) Factory(javax.cache.configuration.Factory) FactoryBuilder(javax.cache.configuration.FactoryBuilder) CacheEntryEventFilter(javax.cache.event.CacheEntryEventFilter) CountDownLatch(java.util.concurrent.CountDownLatch) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom)

Example 3 with ContinuousQuery

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

the class BinaryMetadataUpdatesFlowTest method startListening.

/**
 * @param idx Index.
 * @param deafClient Deaf client.
 * @param observedIds Observed ids.
 */
private void startListening(int idx, boolean deafClient, Set<Integer> observedIds) throws Exception {
    clientMode = true;
    ContinuousQuery qry = new ContinuousQuery();
    qry.setLocalListener(new CQListener(observedIds));
    if (deafClient) {
        applyDiscoveryHook = true;
        discoveryHook = new DiscoveryHook() {

            @Override
            public void handleDiscoveryMessage(DiscoverySpiCustomMessage msg) {
                DiscoveryCustomMessage customMsg = msg == null ? null : (DiscoveryCustomMessage) IgniteUtils.field(msg, "delegate");
                if (customMsg instanceof MetadataUpdateProposedMessage) {
                    if (((MetadataUpdateProposedMessage) customMsg).typeId() == BINARY_TYPE_ID)
                        GridTestUtils.setFieldValue(customMsg, "typeId", 1);
                } else if (customMsg instanceof MetadataUpdateAcceptedMessage) {
                    if (((MetadataUpdateAcceptedMessage) customMsg).typeId() == BINARY_TYPE_ID)
                        GridTestUtils.setFieldValue(customMsg, "typeId", 1);
                }
            }
        };
        IgniteEx client = startGrid(idx);
        client.cache(DEFAULT_CACHE_NAME).withKeepBinary().query(qry);
    } else {
        applyDiscoveryHook = false;
        IgniteEx client = startGrid(idx);
        client.cache(DEFAULT_CACHE_NAME).withKeepBinary().query(qry);
    }
}
Also used : DiscoverySpiCustomMessage(org.apache.ignite.spi.discovery.DiscoverySpiCustomMessage) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) IgniteEx(org.apache.ignite.internal.IgniteEx) DiscoveryCustomMessage(org.apache.ignite.internal.managers.discovery.DiscoveryCustomMessage) DiscoveryHook(org.apache.ignite.testframework.GridTestUtils.DiscoveryHook)

Example 4 with ContinuousQuery

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

the class TcpDiscoveryMultiThreadedTest method _testClientContinuousQueryCoordinatorStop.

/**
 * @throws Exception If failed.
 */
public void _testClientContinuousQueryCoordinatorStop() throws Exception {
    for (int k = 0; k < 10; k++) {
        log.info("Iteration: " + k);
        clientFlagGlobal = false;
        final int START_NODES = 5;
        final int JOIN_NODES = 5;
        startGrids(START_NODES);
        ignite(0).createCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME));
        final AtomicInteger startIdx = new AtomicInteger(START_NODES);
        final CyclicBarrier barrier = new CyclicBarrier(JOIN_NODES + 1);
        clientFlagGlobal = true;
        IgniteInternalFuture<?> fut = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                int idx = startIdx.getAndIncrement();
                Thread.currentThread().setName("start-thread-" + idx);
                barrier.await();
                Ignite ignite = startGrid(idx);
                assertTrue(ignite.configuration().isClientMode());
                log.info("Started node: " + ignite.name());
                IgniteCache<Object, Object> cache = ignite.getOrCreateCache(DEFAULT_CACHE_NAME);
                for (int i = 0; i < 10; i++) {
                    ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
                    qry.setLocalListener(new CacheEntryUpdatedListener<Object, Object>() {

                        @Override
                        public void onUpdated(Iterable<CacheEntryEvent<?, ?>> evts) {
                        // No-op.
                        }
                    });
                    cache.query(qry);
                }
                return null;
            }
        }, JOIN_NODES, "start-thread");
        barrier.await();
        U.sleep(ThreadLocalRandom.current().nextInt(100, 500));
        for (int i = 0; i < START_NODES - 1; i++) {
            GridTestUtils.invoke(ignite(i).configuration().getDiscoverySpi(), "simulateNodeFailure");
            stopGrid(i);
        }
        fut.get();
        stopAllGrids();
    }
}
Also used : IgniteCache(org.apache.ignite.IgniteCache) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) IgniteClientDisconnectedException(org.apache.ignite.IgniteClientDisconnectedException) IgniteClientDisconnectedCheckedException(org.apache.ignite.internal.IgniteClientDisconnectedCheckedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) CyclicBarrier(java.util.concurrent.CyclicBarrier) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CacheEntryUpdatedListener(javax.cache.event.CacheEntryUpdatedListener) Ignite(org.apache.ignite.Ignite)

Example 5 with ContinuousQuery

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

the class SqlViewExporterSpiTest method testContinuousQuery.

/**
 */
@Test
public void testContinuousQuery() throws Exception {
    IgniteCache<Integer, Integer> cache = ignite0.createCache("cache-1");
    assertTrue(execute(ignite0, "SELECT * FROM SYS.CONTINUOUS_QUERIES").isEmpty());
    assertTrue(execute(ignite1, "SELECT * FROM SYS.CONTINUOUS_QUERIES").isEmpty());
    try (QueryCursor qry = cache.query(new ContinuousQuery<>().setInitialQuery(new ScanQuery<>()).setPageSize(100).setTimeInterval(1000).setLocalListener(evts -> {
    // No-op.
    }).setRemoteFilterFactory(() -> evt -> true))) {
        for (int i = 0; i < 100; i++) cache.put(i, i);
        checkContinuouQueryView(ignite0, true);
        checkContinuouQueryView(ignite1, false);
    }
    assertTrue(execute(ignite0, "SELECT * FROM SYS.CONTINUOUS_QUERIES").isEmpty());
    assertTrue(waitForCondition(() -> execute(ignite1, "SELECT * FROM SYS.CONTINUOUS_QUERIES").isEmpty(), getTestTimeout()));
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CacheAtomicityMode(org.apache.ignite.cache.CacheAtomicityMode) Arrays(java.util.Arrays) IgniteJdbcThinDriver(org.apache.ignite.IgniteJdbcThinDriver) StripedExecutor(org.apache.ignite.internal.util.StripedExecutor) Connection(java.sql.Connection) SERIALIZABLE(org.apache.ignite.transactions.TransactionIsolation.SERIALIZABLE) GridCacheUtils.cacheId(org.apache.ignite.internal.processors.cache.GridCacheUtils.cacheId) SqlFieldsQuery(org.apache.ignite.cache.query.SqlFieldsQuery) DistributedMetaStorage(org.apache.ignite.internal.processors.metastorage.DistributedMetaStorage) Transaction(org.apache.ignite.transactions.Transaction) IgniteEx(org.apache.ignite.internal.IgniteEx) METASTORE_VIEW(org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager.METASTORE_VIEW) REPEATABLE_READ(org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ) RendezvousAffinityFunction(org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction) TestObjectEnum(org.apache.ignite.internal.binary.mutabletest.GridBinaryTestClasses.TestObjectEnum) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Arrays.asList(java.util.Arrays.asList) AffinityFunction(org.apache.ignite.cache.affinity.AffinityFunction) AffinityFunctionContext(org.apache.ignite.cache.affinity.AffinityFunctionContext) GridDhtPartitionState(org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionState) IgniteUtils.toStringSafe(org.apache.ignite.internal.util.IgniteUtils.toStringSafe) CyclicBarrier(java.util.concurrent.CyclicBarrier) SystemView(org.apache.ignite.spi.systemview.view.SystemView) Collection(java.util.Collection) Set(java.util.Set) SCHEMA_SYS(org.apache.ignite.internal.processors.query.QueryUtils.SCHEMA_SYS) OPTIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) IgniteCache(org.apache.ignite.IgniteCache) GridTestUtils(org.apache.ignite.testframework.GridTestUtils) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) ClientConfiguration(org.apache.ignite.configuration.ClientConfiguration) TEST_TRANSFORMER(org.apache.ignite.internal.metric.SystemViewSelfTest.TEST_TRANSFORMER) DFLT_SCHEMA(org.apache.ignite.internal.processors.query.QueryUtils.DFLT_SCHEMA) QueryCursor(org.apache.ignite.cache.query.QueryCursor) PESSIMISTIC(org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC) DummyService(org.apache.ignite.internal.processors.service.DummyService) ScanQuery(org.apache.ignite.cache.query.ScanQuery) GridCacheUtils.cacheGroupId(org.apache.ignite.internal.processors.cache.GridCacheUtils.cacheGroupId) GridTestUtils.waitForCondition(org.apache.ignite.testframework.GridTestUtils.waitForCondition) AbstractExporterSpiTest(org.apache.ignite.internal.metric.AbstractExporterSpiTest) ArrayList(java.util.ArrayList) SqlSchemaView(org.apache.ignite.spi.systemview.view.SqlSchemaView) HashSet(java.util.HashSet) DISTRIBUTED_METASTORE_VIEW(org.apache.ignite.internal.processors.metastorage.persistence.DistributedMetaStorageImpl.DISTRIBUTED_METASTORE_VIEW) GridCacheDatabaseSharedManager(org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager) ClusterNode(org.apache.ignite.cluster.ClusterNode) IgniteClient(org.apache.ignite.client.IgniteClient) TestRunnable(org.apache.ignite.internal.metric.SystemViewSelfTest.TestRunnable) IgnitePredicate(org.apache.ignite.lang.IgnitePredicate) AbstractSchemaSelfTest.queryProcessor(org.apache.ignite.internal.processors.cache.index.AbstractSchemaSelfTest.queryProcessor) DataStorageConfiguration(org.apache.ignite.configuration.DataStorageConfiguration) TEST_PREDICATE(org.apache.ignite.internal.metric.SystemViewSelfTest.TEST_PREDICATE) SQL_SCHEMA_VIEW(org.apache.ignite.internal.processors.query.h2.SchemaManager.SQL_SCHEMA_VIEW) ServiceConfiguration(org.apache.ignite.services.ServiceConfiguration) TestTransformer(org.apache.ignite.internal.metric.SystemViewSelfTest.TestTransformer) MetastorageView(org.apache.ignite.spi.systemview.view.MetastorageView) SqlConfiguration(org.apache.ignite.configuration.SqlConfiguration) TestPredicate(org.apache.ignite.internal.metric.SystemViewSelfTest.TestPredicate) G(org.apache.ignite.internal.util.typedef.G) F(org.apache.ignite.internal.util.typedef.F) Properties(java.util.Properties) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) Test(org.junit.Test) Ignite(org.apache.ignite.Ignite) Field(java.lang.reflect.Field) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) TestObjectAllTypes(org.apache.ignite.internal.binary.mutabletest.GridBinaryTestClasses.TestObjectAllTypes) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) IgniteCacheDatabaseSharedManager(org.apache.ignite.internal.processors.cache.persistence.IgniteCacheDatabaseSharedManager) Ignition(org.apache.ignite.Ignition) CacheConfiguration(org.apache.ignite.configuration.CacheConfiguration) DataRegionConfiguration(org.apache.ignite.configuration.DataRegionConfiguration) CacheMode(org.apache.ignite.cache.CacheMode) ContinuousQuery(org.apache.ignite.cache.query.ContinuousQuery) ScanQuery(org.apache.ignite.cache.query.ScanQuery) QueryCursor(org.apache.ignite.cache.query.QueryCursor) AbstractExporterSpiTest(org.apache.ignite.internal.metric.AbstractExporterSpiTest) 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