org.apache.ignite.IgniteCache Java Examples
The following examples show how to use
org.apache.ignite.IgniteCache.
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: IgniteCacheReadThroughEvictionSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** * @throws Exception if failed. */ @Ignore("https://issues.apache.org/jira/browse/IGNITE-11849") @Test public void testReadThroughSkipStore() throws Exception { Ignite ig = testedGrid(); CacheConfiguration<Object, Object> cc = variationConfig("skipStore"); final IgniteCache<Object, Object> cache = ig.createCache(cc); try { for (int i = 0; i < KEYS; i++) { cache.put(key(i), value(i)); cache.withSkipStore().remove(key(i)); } waitEmpty(cc.getName()); for (int i = 0; i < KEYS; i++) assertEquals(value(i), cache.get(key(i))); } finally { destroyCacheSafe(ig, cc.getName()); } }
Example #2
Source File: IgniteSqlSegmentedIndexSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** * Verifies that <code>select count(*)</code> return valid result on a single-node grid. */ @SuppressWarnings("deprecation") @Test public void testSizeOnSegmentedIndexWithEvictionPolicy() { final IgniteCache<Object, Object> cache = ignite(0).createCache( cacheConfig(ORG_CACHE_NAME, true, Integer.class, Organization.class) .setEvictionPolicy(new FifoEvictionPolicy(10)) .setOnheapCacheEnabled(true)); final long SIZE = 20; for (int i = 0; i < SIZE; i++) cache.put(i, new Organization("org-" + i)); String select0 = "select count(*) from \"org\".Organization"; List<List<?>> res = cache.query(new SqlFieldsQuery(select0)).getAll(); assertEquals(SIZE, res.get(0).get(0)); }
Example #3
Source File: LongRunningQueryTest.java From ignite with Apache License 2.0 | 6 votes |
/** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); startGrid(); IgniteCache c = grid().createCache(new CacheConfiguration<Long, Long>() .setName("test") .setSqlSchema("TEST") .setQueryEntities(Collections.singleton(new QueryEntity(Long.class, Long.class) .setTableName("test") .addQueryField("id", Long.class.getName(), null) .addQueryField("val", Long.class.getName(), null) .setKeyFieldName("id") .setValueFieldName("val") )) .setAffinity(new RendezvousAffinityFunction(false, 10)) .setSqlFunctionClasses(TestSQLFunctions.class)); for (long i = 0; i < KEY_CNT; ++i) c.put(i, i); }
Example #4
Source File: GridCacheBinaryObjectsAbstractSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** * @throws Exception If failed. */ @Test public void testGet() throws Exception { IgniteCache<Integer, TestObject> c = jcache(0); for (int i = 0; i < ENTRY_CNT; i++) c.put(i, new TestObject(i)); for (int i = 0; i < ENTRY_CNT; i++) { TestObject obj = c.get(i); assertEquals(i, obj.val); } IgniteCache<Integer, BinaryObject> kpc = keepBinaryCache(); for (int i = 0; i < ENTRY_CNT; i++) { BinaryObject po = kpc.get(i); assertEquals(i, (int)po.field("val")); } }
Example #5
Source File: IgniteKernal.java From ignite with Apache License 2.0 | 6 votes |
/** {@inheritDoc} */ @Override public <K, V> IgniteCache<K, V> createCache(String cacheName) { CU.validateNewCacheName(cacheName); guard(); try { checkClusterState(); ctx.cache().createFromTemplate(cacheName).get(); return ctx.cache().publicJCache(cacheName); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } finally { unguard(); } }
Example #6
Source File: DhtAndNearEvictionTest.java From ignite with Apache License 2.0 | 6 votes |
/** * Checking rebalancing which used to be affected by IGNITE-9315. */ @Test public void testRebalancing() throws Exception { Ignite grid0 = startGrid(0); CacheConfiguration<Integer, Integer> ccfg = new CacheConfiguration<Integer, Integer>("mycache") .setOnheapCacheEnabled(true) .setEvictionPolicyFactory(new LruEvictionPolicyFactory<>(500)) .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL) .setNearConfiguration( new NearCacheConfiguration<Integer, Integer>() .setNearEvictionPolicyFactory(new LruEvictionPolicyFactory<>(100)) ); IgniteCache<Integer, Integer> cache = grid0.createCache(ccfg); for (int i = 0; i < 1000; i++) cache.put(i, i); startGrid(1); awaitPartitionMapExchange(true, true, null); assertFalse(strLog.toString().contains("AssertionError")); }
Example #7
Source File: RestBinaryProtocolSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** * @throws Exception If failed. */ @Test public void testReplace() throws Exception { assertFalse(client.cacheReplace(DEFAULT_CACHE_NAME, "key1", "val1")); IgniteCache<Object, Object> jcacheDflt = grid().cache(DEFAULT_CACHE_NAME); jcacheDflt.put("key1", "val1"); assertTrue(client.cacheReplace(DEFAULT_CACHE_NAME, "key1", "val2")); assertFalse(client.cacheReplace(DEFAULT_CACHE_NAME, "key2", "val1")); jcacheDflt.put("key2", "val1"); assertTrue(client.cacheReplace(DEFAULT_CACHE_NAME, "key2", "val2")); jcacheDflt.clear(); assertFalse(client.cacheReplace(CACHE_NAME, "key1", "val1")); grid().cache(CACHE_NAME).put("key1", "val1"); assertTrue(client.cacheReplace(CACHE_NAME, "key1", "val2")); }
Example #8
Source File: GridIndexingWithNoopSwapSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** @throws Exception If failed. */ @Test public void testQuery() throws Exception { IgniteCache<Integer, ObjectValue> cache = ignite.cache(DEFAULT_CACHE_NAME); int cnt = 10; for (int i = 0; i < cnt; i++) cache.getAndPut(i, new ObjectValue("test" + i, i)); for (int i = 0; i < cnt; i++) { assertNotNull(cache.localPeek(i, ONHEAP_PEEK_MODES)); cache.localEvict(Collections.singleton(i)); // Swap. } SqlQuery<Integer, ObjectValue> qry = new SqlQuery(ObjectValue.class, "intVal >= ? order by intVal"); assertEquals(10, cache.query(qry.setArgs(0)).getAll().size()); }
Example #9
Source File: H2ConnectionLeaksSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** * @throws Exception On failed. */ @Test public void testExplainLeak() throws Exception { startGridAndPopulateCache(NODE_CNT); final IgniteCache cache = grid(0).cache(CACHE_NAME); for (int i = 0; i < ITERS; ++i) { GridTestUtils.runMultiThreaded(() -> { cache.query(new SqlFieldsQuery("explain select * from String")).getAll(); }, 10, "explain-threads"); checkThereAreNotUsedConnections(); } }
Example #10
Source File: CacheManager.java From ignite with Apache License 2.0 | 6 votes |
/** {@inheritDoc} */ @Override public void enableManagement(String cacheName, boolean enabled) { if (IgniteUtils.IGNITE_MBEANS_DISABLED) return; kernalGateway.readLock(); try { IgniteCache<?, ?> cache = getCache0(cacheName); if (cache == null) throw new CacheException("Cache not found: " + cacheName); if (enabled) registerCacheObject(cache.mxBean(), cacheName, CACHE_CONFIGURATION); else unregisterCacheObject(cacheName, CACHE_CONFIGURATION); cache.getConfiguration(CacheConfiguration.class).setManagementEnabled(enabled); } finally { kernalGateway.readUnlock(); } }
Example #11
Source File: GridCacheP2PUndeploySelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** * @param cache Cache. * @param timeout Timeout. * @return {@code True} if success. * @throws InterruptedException If thread was interrupted. */ @SuppressWarnings({"BusyWait"}) private boolean waitCacheEmpty(IgniteCache<Integer, Object> cache, long timeout) throws InterruptedException { assert cache != null; assert timeout >= 0; long end = System.currentTimeMillis() + timeout; while (end - System.currentTimeMillis() >= 0) { if (cache.localSize() == 0) return true; Thread.sleep(500); } return cache.localSize() == 0; }
Example #12
Source File: IgniteSqlSegmentedIndexSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** * Run tests on single-node grid. */ @SuppressWarnings("deprecation") @Test public void testSegmentedIndexWithEvictionPolicy() { final IgniteCache<Object, Object> cache = ignite(0).createCache( cacheConfig(ORG_CACHE_NAME, true, Integer.class, Organization.class) .setEvictionPolicy(new FifoEvictionPolicy(10)) .setOnheapCacheEnabled(true)); final long SIZE = 20; for (int i = 0; i < SIZE; i++) cache.put(i, new Organization("org-" + i)); String select0 = "select name from \"org\".Organization"; List<List<?>> res = cache.query(new SqlFieldsQuery(select0)).getAll(); assertEquals(SIZE, res.size()); }
Example #13
Source File: IgniteSqlKeyValueFieldsTest.java From ignite with Apache License 2.0 | 6 votes |
/** Check that joins are working on keyFieldName, valueFieldName columns */ @Test public void testJoinKeyValFields() throws Exception { IgniteEx client = grid(NODE_CLIENT); IgniteCache<Integer, Person> cache = client.cache(CACHE_PERSON); IgniteCache<Integer, Integer> cache2 = client.cache(CACHE_JOB); checkInsert(cache, "insert into Person (id, v) values (?, ?)", 1, new Person("Bob", 30)); checkInsert(cache, "insert into Person (id, v) values (?, ?)", 2, new Person("David", 35)); checkInsert(cache2, "insert into Integer (_key, _val) values (?, ?)", 100, 1); checkInsert(cache2, "insert into Integer (_key, _val) values (?, ?)", 200, 2); QueryCursor<List<?>> cursor = cache.query(new SqlFieldsQuery("select p.id, j._key from Person p, \"" + CACHE_JOB + "\".Integer j where p.id = j._val")); List<List<?>> results = cursor.getAll(); assertEquals(2, results.size()); assertEquals(1, results.get(0).get(0)); assertEquals(100, results.get(0).get(1)); assertEquals(2, results.get(1).get(0)); assertEquals(200, results.get(1).get(1)); }
Example #14
Source File: GridCacheAbstractMetricsSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** * @throws IgniteCheckedException If failed. */ @Test public void testInvokeAllAsyncAvgTime() throws IgniteCheckedException { IgniteCache<Integer, Integer> cache = grid(0).cache(DEFAULT_CACHE_NAME); assertEquals(0.0, cache.localMetrics().getEntryProcessorAverageInvocationTime(), 0.001f); Map<Integer, EntryProcessorResult<Object>> invokeFut = cache.invokeAllAsync( ImmutableMap.of(0, updatingProcessor, 1, readingProcessor, 2, removingProcessor)).get(); U.sleep(100); assertTrue(cache.localMetrics().getEntryProcessorAverageInvocationTime() > 0.0); }
Example #15
Source File: BaseSqlTest.java From ignite with Apache License 2.0 | 6 votes |
/** * Check greater operator in where clause with both indexed and non-indexed field. */ @Test public void testWhereGreater() { testAllNodes(node -> { Result idxActual = executeFrom("SELECT firstName FROM Employee WHERE age > 30", node); Result noidxActual = executeFrom("SELECT firstName FROM Employee WHERE salary > 75", node); IgniteCache<Object, Object> cache = node.cache(EMP_CACHE_NAME); List<List<Object>> idxExp = select(cache, row -> (Integer)row.get("AGE") > 30, "firstName"); List<List<Object>> noidxExp = select(cache, row -> (Integer)row.get("SALARY") > 75, "firstName"); assertContainsEq(idxActual.values(), idxExp); assertContainsEq(noidxActual.values(), noidxExp); }); }
Example #16
Source File: GridCacheTransactionalAbstractMetricsSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** */ @Test public void testCommitTime() { IgniteCache<Integer, Integer> cache = grid(0).cache(DEFAULT_CACHE_NAME); HistogramMetricImpl m = metric("CommitTime"); assertTrue(Arrays.stream(m.value()).allMatch(v -> v == 0)); try (Transaction tx = grid(0).transactions().txStart()) { cache.put(1, 1); tx.commit(); } assertEquals(1, Arrays.stream(m.value()).filter(v -> v == 1).count()); }
Example #17
Source File: IgniteSqlGroupConcatNotCollocatedTest.java From ignite with Apache License 2.0 | 6 votes |
/** * */ @Test public void testGroupConcatCountDistinct() { IgniteCache c = ignite(CLIENT).cache(CACHE_NAME); List<List<Object>> res = c.query( new SqlFieldsQuery("select count(distinct str0), group_concat(str0) from Value group by grp")).getAll(); for (List<Object> row : res) { long cnt = (long)row.get(0); String str = (String)row.get(1); for (int i = 0; i < cnt; ++i) { String s = "" + (char)('A' + i + (cnt - 1) * cnt / 2); assertTrue("Invalid group_concat result: string doesn't contain value: " + "[str=" + str + ", val=" + s, str.contains(s)); } } }
Example #18
Source File: RunningQueriesTest.java From ignite with Apache License 2.0 | 6 votes |
/** * Check cleanup running queries on node stop. * * @throws Exception Exception in case of failure. */ @Test public void testCloseRunningQueriesOnNodeStop() throws Exception { IgniteEx ign = startGrid(super.getConfiguration("TST")); IgniteCache<Integer, Integer> cache = ign.getOrCreateCache(new CacheConfiguration<Integer, Integer>() .setName("TST") .setQueryEntities(Collections.singletonList(new QueryEntity(Integer.class, Integer.class))) ); for (int i = 0; i < 10000; i++) cache.put(i, i); cache.query(new SqlFieldsQuery("SELECT * FROM Integer order by _key")); Assert.assertEquals("Should be one running query", 1, ign.context().query().runningQueries(-1).size()); ign.close(); Assert.assertEquals(0, ign.context().query().runningQueries(-1).size()); }
Example #19
Source File: CacheOptimisticTransactionsWithFilterTest.java From ignite with Apache License 2.0 | 6 votes |
/** * @param cache Cache. * @return Test keys. * @throws Exception If failed. */ private List<Integer> testKeys(IgniteCache<Integer, Integer> cache) throws Exception { CacheConfiguration ccfg = cache.getConfiguration(CacheConfiguration.class); List<Integer> keys = new ArrayList<>(); if (!cache.unwrap(Ignite.class).configuration().isClientMode()) { if (ccfg.getCacheMode() == PARTITIONED && serversNumber() > 1) keys.add(nearKey(cache)); keys.add(primaryKey(cache)); if (ccfg.getBackups() != 0 && serversNumber() > 1) keys.add(backupKey(cache)); } else keys.add(nearKey(cache)); return keys; }
Example #20
Source File: SqlPartOfComplexPkLookupTest.java From ignite with Apache License 2.0 | 6 votes |
/** */ @Test public void testPartOfComplexPkLookupDdl() throws Exception { IgniteEx ign = startGrid(0); IgniteCache<Object, Object> cache = ign.getOrCreateCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME)); cache.query(new SqlFieldsQuery("" + "CREATE TABLE Person(\n" + " id int,\n" + " city_id int,\n" + " name varchar,\n" + " PRIMARY KEY (id, city_id)\n" + ");")); cache.query(new SqlFieldsQuery("INSERT INTO Person (id, city_id, name) VALUES (1, 3, 'John Doe');")); cache.query(new SqlFieldsQuery("INSERT INTO Person (id, city_id, name) VALUES (1, 4, 'John Dean');")); checkPartialPkLookup(cache); }
Example #21
Source File: IgniteTxConfigCacheSelfTest.java From ignite with Apache License 2.0 | 5 votes |
/** * Success if explicit tx fails. * * @param cache Cache name. * @param ignite Ignite instance. * @throws Exception If failed. */ protected void checkExplicitTxTimeout(final IgniteCache<Object, Object> cache, final Ignite ignite) throws Exception { try (final Transaction tx = ignite.transactions().txStart()) { assert tx != null; cache.put("key0", "val0"); sleepForTxFailure(); cache.put("key", "val"); fail("Timeout exception must be thrown"); } catch (CacheException e) { assert e.getCause() instanceof TransactionTimeoutException; } assertNull(ignite.transactions().tx()); assert !cache.containsKey("key0"); assert !cache.containsKey("key"); // New transaction must succeed. try (final Transaction tx = ignite.transactions().txStart()) { cache.put("key", "val"); tx.commit(); } assert cache.containsKey("key"); }
Example #22
Source File: GridCacheNearEvictionSelfTest.java From ignite with Apache License 2.0 | 5 votes |
/** @throws Exception If failed. */ @Test public void testNearEnabledTwoNodes() throws Exception { gridCnt = 2; startGridsMultiThreaded(gridCnt); try { final int cnt = 100; grid(0).compute().broadcast(new IgniteCallable<Object>() { @IgniteInstanceResource private Ignite ignite; @Override public Object call() throws Exception { IgniteCache<Integer, String> c = ignite.cache(DEFAULT_CACHE_NAME); for (int i = 0; i < cnt; i++) c.put(i, Integer.toString(i)); return true; } }); for (int i = 0; i < gridCnt; i++) { assertEquals(cnt, internalCache(i).size()); assertEquals(0, near(i).nearSize()); } } finally { stopAllGrids(); } }
Example #23
Source File: IndexingSpiQueryTxSelfTest.java From ignite with Apache License 2.0 | 5 votes |
/** * @throws Exception If failed. */ private void doTestIndexingSpiWithTx(IgniteEx ignite, int key) throws Exception { final IgniteCache<Integer, Integer> cache = ignite.cache(DEFAULT_CACHE_NAME); final IgniteTransactions txs = ignite.transactions(); for (final TransactionConcurrency concurrency : TransactionConcurrency.values()) { for (final TransactionIsolation isolation : TransactionIsolation.values()) { System.out.println("Run in transaction: " + concurrency + " " + isolation); GridTestUtils.assertThrowsWithCause(new Callable<Void>() { @Override public Void call() throws Exception { Transaction tx; try (Transaction tx0 = tx = txs.txStart(concurrency, isolation)) { cache.put(key, key); tx0.commit(); } assertEquals(TransactionState.ROLLED_BACK, tx.state()); return null; } }, IgniteTxHeuristicCheckedException.class); checkFutures(); } } }
Example #24
Source File: IgniteSqlQueryPutSeparatedBenchmark.java From ignite with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override public boolean test(Map<Object, Object> ctx) throws Exception { ThreadLocalRandom rnd = ThreadLocalRandom.current(); if (cfg.memberId() % 2 == 0) { double salary = rnd.nextDouble() * args.range() * 1000; double maxSalary = salary + 1000; Collection<Cache.Entry<Integer, Object>> entries = executeQuery(salary, maxSalary); for (Cache.Entry<Integer, Object> entry : entries) { Person p = (Person)entry.getValue(); if (p.getSalary() < salary || p.getSalary() > maxSalary) throw new Exception("Invalid person retrieved [min=" + salary + ", max=" + maxSalary + ", person=" + p + ']'); } } else { IgniteCache<Integer, Object> cache = cacheForOperation(true); int i = rnd.nextInt(args.range()); cache.put(i, new Person(i, "firstName" + i, "lastName" + i, i * 1000)); } return true; }
Example #25
Source File: CacheStoreSessionListenerReadWriteThroughDisabledAbstractTest.java From ignite with Apache License 2.0 | 5 votes |
/** * Tests that there are no calls of {@link CacheStoreSessionListener#onSessionStart(CacheStoreSession)} and * {@link CacheStoreSessionListener#onSessionStart(CacheStoreSession)} * while {@link IgniteCache#putAll(Map)} performed. * * @throws Exception If failed. */ @Test public void testBatchUpdate() throws Exception { IgniteCache<Object, Object> cache = grid(0).getOrCreateCache(DEFAULT_CACHE_NAME); Random r = new Random(); Map<Object, Object> values = new TreeMap<>(); for (int i = 0; i < CNT; ++i) values.put(r.nextInt(), "test-value"); cache.putAll(values); }
Example #26
Source File: ClientCacheGetConfigurationRequest.java From ignite with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public ClientResponse process(ClientConnectionContext ctx) { CacheConfiguration cfg = ((IgniteCache<Object, Object>) rawCache(ctx)) .getConfiguration(CacheConfiguration.class); return new ClientCacheGetConfigurationResponse(requestId(), cfg, protocolCtx); }
Example #27
Source File: LogRegFromSparkThroughPMMLExample.java From ignite with Apache License 2.0 | 5 votes |
/** Run example. */ public static void main(String[] args) throws IOException { System.out.println(); System.out.println(">>> Logistic regression model loaded from PMML over partitioned dataset usage example started."); // Start ignite grid. try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(">>> Ignite grid started."); IgniteCache<Integer, Vector> dataCache = null; try { Vectorizer<Integer, Vector, Integer, Double> vectorizer = new DummyVectorizer<Integer>() .labeled(Vectorizer.LabelCoordinate.FIRST); dataCache = new SandboxMLCache(ignite).fillCacheWith(MLSandboxDatasets.TWO_CLASSED_IRIS); String path = IgniteUtils.resolveIgnitePath("examples/src/main/resources/models/spark/iris.pmml") .toPath().toAbsolutePath().toString(); LogisticRegressionModel mdl = PMMLParser.load(path); System.out.println(">>> Logistic regression model: " + mdl); double accuracy = Evaluator.evaluate( dataCache, mdl, vectorizer, new Accuracy<>() ); System.out.println("\n>>> Accuracy " + accuracy); System.out.println("\n>>> Test Error " + (1 - accuracy)); } finally { if (dataCache != null) dataCache.destroy(); } } }
Example #28
Source File: IgniteCacheConfigVariationsQueryTest.java From ignite with Apache License 2.0 | 5 votes |
/** * @throws Exception If failed. */ @SuppressWarnings("serial") @Test public void testScanQuery() throws Exception { runInAllDataModes(new TestRunnable() { @Override public void run() throws Exception { try { IgniteCache<Object, Object> cache = jcache(); Map<Object, Object> map = new HashMap<Object, Object>() {{ for (int i = 0; i < CNT; i++) put(key(i), value(i)); }}; registerEventListeners(map); for (Map.Entry<Object, Object> e : map.entrySet()) cache.put(e.getKey(), e.getValue()); // Scan query. QueryCursor<Cache.Entry<Object, Object>> qry = cache.query(new ScanQuery()); checkQueryResults(map, qry); } finally { stopListeners(); } } }); }
Example #29
Source File: IgniteCachePartitionedAtomicColumnConstraintsTest.java From ignite with Apache License 2.0 | 5 votes |
/** * @throws Exception If failed. */ @Test public void testPutTooLongDecimalKeyFail() throws Exception { IgniteCache<BigDecimal, BigDecimal> cache = jcache(0, DEC_CACHE_NAME_FOR_PREC); T2<BigDecimal, BigDecimal> val = new T2<>(d(123.45), d(12.34)); checkPutAll(shouldFail, cache, new T2<>(d(12.35), d(12.34)), val); checkPutOps(shouldFail, cache, val); }
Example #30
Source File: GridCacheAbstractPartitionedOnlyByteArrayValuesSelfTest.java From ignite with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); int gridCnt = gridCount(); cachesAtomic = new IgniteCache[gridCnt]; for (int i = 0; i < gridCount(); i++) cachesAtomic[i] = grid(i).cache(ATOMIC_CACHE); }