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

The following examples show how to use org.apache.ignite.IgniteCache#getAll() . 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: CachePutGetExample.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Execute bulk {@code putAll(...)} and {@code getAll(...)} operations.
 *
 * @throws IgniteException If failed.
 */
private static void putAllGetAll(IgniteCache<Integer, String> cache) throws IgniteException {
    System.out.println();
    System.out.println(">>> Starting putAll-getAll example.");

    final int keyCnt = 20;

    // Create batch.
    Map<Integer, String> batch = new HashMap<>();

    for (int i = 0; i < keyCnt; i++)
        batch.put(i, "bulk-" + Integer.toString(i));

    // Bulk-store entries in cache.
    cache.putAll(batch);

    System.out.println(">>> Bulk-stored values in cache.");

    // Bulk-get values from cache.
    Map<Integer, String> vals = cache.getAll(batch.keySet());

    for (Map.Entry<Integer, String> e : vals.entrySet())
        System.out.println("Got entry [key=" + e.getKey() + ", val=" + e.getValue() + ']');
}
 
Example 2
Source File: CacheClientStoreSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
private void doTestNoStore() throws Exception {
    factory = null;

    Ignite ignite = startClientGrid("client-1");

    IgniteCache<Object, Object> cache = ignite.cache(CACHE_NAME);

    cache.get(0);
    cache.getAll(F.asSet(0, 1));
    cache.getAndPut(0, 0);
    cache.getAndPutIfAbsent(0, 0);
    cache.getAndRemove(0);
    cache.getAndReplace(0, 0);
    cache.put(0, 0);
    cache.putAll(F.asMap(0, 0, 1, 1));
    cache.putIfAbsent(0, 0);
    cache.remove(0);
    cache.remove(0, 0);
    cache.removeAll(F.asSet(0, 1));
    cache.removeAll();
    cache.invoke(0, new EP());
    cache.invokeAll(F.asSet(0, 1), new EP());
}
 
Example 3
Source File: IgniteCacheGetRestartTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param cache Cache.
 */
private void checkGet(IgniteCache<Object, Object> cache) {
    for (int i = 0; i < KEYS; i++)
        assertEquals(i, cache.get(i));

    Set<Integer> keys = new HashSet<>();

    for (int i = 0; i < KEYS; i++) {
        keys.add(i);

        if (keys.size() == 100) {
            Map<Object, Object> vals = cache.getAll(keys);

            for (Object key : keys)
                assertEquals(key, vals.get(key));

            keys.clear();
        }
    }
}
 
Example 4
Source File: CacheClientBinaryPutGetExample.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Execute bulk {@code putAll(...)} and {@code getAll(...)} operations,
 * getting values in binary format, without de-serializing it.
 *
 * @param cache Cache.
 */
private static void putGetAllBinary(IgniteCache<Integer, Organization> cache) {
    // Create new Organization binary objects to store in cache.
    Organization org1 = new Organization(
        "Microsoft", // Name.
        new Address("1096 Eddy Street, San Francisco, CA", 94109), // Address.
        OrganizationType.PRIVATE, // Type.
        new Timestamp(System.currentTimeMillis())); // Last update time.

    Organization org2 = new Organization(
        "Red Cross", // Name.
        new Address("184 Fidler Drive, San Antonio, TX", 78205), // Address.
        OrganizationType.NON_PROFIT, // Type.
        new Timestamp(System.currentTimeMillis())); // Last update time.

    Map<Integer, Organization> map = new HashMap<>();

    map.put(1, org1);
    map.put(2, org2);

    // Put created data entries to cache.
    cache.putAll(map);

    // Get cache that will get values as binary objects.
    IgniteCache<Integer, BinaryObject> binaryCache = cache.withKeepBinary();

    // Get recently created organizations as binary objects.
    Map<Integer, BinaryObject> poMap = binaryCache.getAll(map.keySet());

    Collection<String> names = new ArrayList<>();

    // Get organizations' names from binary objects (note that
    // objects don't need to be fully deserialized).
    for (BinaryObject po : poMap.values())
        names.add(po.<String>field("name"));

    System.out.println();
    System.out.println(">>> Retrieved organization names from binary objects: " + names);
}
 
Example 5
Source File: CacheClientBinaryPutGetExample.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Execute bulk {@code putAll(...)} and {@code getAll(...)} operations.
 *
 * @param cache Cache.
 */
private static void putGetAll(IgniteCache<Integer, Organization> cache) {
    // Create new Organization binary objects to store in cache.
    Organization org1 = new Organization(
        "Microsoft", // Name.
        new Address("1096 Eddy Street, San Francisco, CA", 94109), // Address.
        OrganizationType.PRIVATE, // Type.
        new Timestamp(System.currentTimeMillis())); // Last update time.

    Organization org2 = new Organization(
        "Red Cross", // Name.
        new Address("184 Fidler Drive, San Antonio, TX", 78205), // Address.
        OrganizationType.NON_PROFIT, // Type.
        new Timestamp(System.currentTimeMillis())); // Last update time.

    Map<Integer, Organization> map = new HashMap<>();

    map.put(1, org1);
    map.put(2, org2);

    // Put created data entries to cache.
    cache.putAll(map);

    // Get recently created organizations as a strongly-typed fully de-serialized instances.
    Map<Integer, Organization> mapFromCache = cache.getAll(map.keySet());

    System.out.println();
    System.out.println(">>> Retrieved organization instances from cache:");

    for (Organization org : mapFromCache.values())
        System.out.println(">>>     " + org);
}
 
Example 6
Source File: IgniteCacheRandomOperationBenchmark.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param cache Ignite cache.
 * @throws Exception If failed.
 */
private void doGetAll(IgniteCache<Object, Object> cache) throws Exception {
    Set<Object> keys = new TreeSet<>();

    Class keyCls = randomKeyClass(cache.getName());

    for (int cnt = 0; cnt < args.batch(); cnt++) {
        int i = nextRandom(args.range());

        keys.add(ModelUtil.create(keyCls, i));
    }

    cache.getAll(keys);
}
 
Example 7
Source File: CacheEntryProcessorExample.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Prints out all the entries that are stored in a cache.
 *
 * @param cache Cache.
 */
private static void printCacheEntries(IgniteCache<Integer, Integer> cache) {
    System.out.println();
    System.out.println(">>> Entries in the cache.");

    Map<Integer, Integer> entries = cache.getAll(KEYS_SET);

    if (entries.isEmpty())
        System.out.println("No entries in the cache.");
    else {
        for (Map.Entry<Integer, Integer> entry : entries.entrySet())
            System.out.println("Entry [key=" + entry.getKey() + ", value=" + entry.getValue() + ']');
    }
}
 
Example 8
Source File: CacheMvccTransactionsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Reads value from cache for the given key using given read mode.
 *
 * // TODO IGNITE-6938 remove inTx flag
 * // TODO IGNITE-6739 add SQL-get support "select _key, _val from cache where _key in ... keySet"
 * @param inTx Flag whether current read is inside transaction.
 * This is because reads can't see writes made in current transaction.
 * @param cache Cache.
 * @param keys Key.
 * @param readMode Read mode.
 * @return Value.
 */
private Map getAllByReadMode(boolean inTx, IgniteCache cache, Set keys, ReadMode readMode) {

    // TODO Remove in IGNITE-6938
    if (inTx)
        readMode = GET;

    switch (readMode) {
        case GET:
            return cache.getAll(keys);

        case SCAN:
            Map res = (Map)cache.query(new ScanQuery(new IgniteBiPredicate() {
                @Override public boolean apply(Object k, Object v) {
                    return keys.contains(k);
                }
            })).getAll()
                .stream()
                .collect(Collectors.toMap(v -> ((IgniteBiTuple)v).getKey(), v -> ((IgniteBiTuple)v).getValue()));

            assertTrue(res.size() <= keys.size());

            return res;

        default:
            throw new IgniteException("Unsupported read mode: " + readMode);
    }
}
 
Example 9
Source File: CacheClientStoreSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testCorrectStore() throws Exception {
    nearEnabled = false;
    cacheMode = CacheMode.PARTITIONED;
    factory = new Factory1();

    startGrids(2);

    Ignite ignite = startClientGrid("client-1");

    IgniteCache<Object, Object> cache = ignite.cache(CACHE_NAME);

    cache.get(0);
    cache.getAll(F.asSet(0, 1));
    cache.getAndPut(0, 0);
    cache.getAndPutIfAbsent(0, 0);
    cache.getAndRemove(0);
    cache.getAndReplace(0, 0);
    cache.put(0, 0);
    cache.putAll(F.asMap(0, 0, 1, 1));
    cache.putIfAbsent(0, 0);
    cache.remove(0);
    cache.remove(0, 0);
    cache.removeAll(F.asSet(0, 1));
    cache.removeAll();
    cache.invoke(0, new EP());
    cache.invokeAll(F.asSet(0, 1), new EP());
}
 
Example 10
Source File: IgniteCacheStoreCollectionTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param cache Cache.
 */
private void checkStoreMap(IgniteCache<Object, Object> cache) {
    cache.put(1, new MyMap());
    cache.put(2, new MyMap());

    MyMap map = (MyMap)cache.get(1);

    assertNotNull(map);

    Map<Integer, MyMap> vals = (Map)cache.getAll(F.asSet(1, 2));

    assertEquals(2, vals.size());
    assertTrue("Unexpected value: " + vals.get(1), vals.get(1) instanceof MyMap);
    assertTrue("Unexpected value: " + vals.get(2), vals.get(2) instanceof MyMap);
}
 
Example 11
Source File: CacheStoreSessionListenerReadWriteThroughDisabledAbstractTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that there are no calls of {@link CacheStoreSessionListener#onSessionStart(CacheStoreSession)} and
 * {@link CacheStoreSessionListener#onSessionStart(CacheStoreSession)}
 * while {@link IgniteCache#getAll(Set)} performed.
 *
 * @throws Exception If failed.
 */
@Test
public void testBatchLookup() throws Exception {
    IgniteCache<Object, Object> cache = grid(0).getOrCreateCache(DEFAULT_CACHE_NAME);

    Random r = new Random();

    Set<Object> values = new HashSet<>();

    for (int i = 0; i < CNT; ++i)
        values.add(r.nextInt());

    cache.getAll(values);
}
 
Example 12
Source File: IgniteCachePrimarySyncTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param cache Cache.
 * @param txs Transactions instance if explicit transaction should be used.
 * @param concurrency Transaction concurrency.
 * @param isolation Transaction isolation.
 */
private void checkPutGet(IgniteCache<Object, Object> cache,
    @Nullable IgniteTransactions txs,
    TransactionConcurrency concurrency,
    TransactionIsolation isolation) {
    log.info("Check cache: " + cache.getName());

    final int KEYS = 50;

    for (int iter = 0; iter < 100; iter++) {
        if (iter % 10 == 0)
            log.info("Iteration: " + iter);

        for (int i = 0; i < KEYS; i++)
            cache.remove(i);

        Map<Integer, Integer> putBatch = new HashMap<>();

        for (int i = 0; i < KEYS; i++)
            putBatch.put(i, iter);

        if (txs != null) {
            try (Transaction tx = txs.txStart(concurrency, isolation)) {
                cache.putAll(putBatch);

                tx.commit();
            }
        }
        else
            cache.putAll(putBatch);

        Map<Object, Object> vals = cache.getAll(putBatch.keySet());

        for (int i = 0; i < KEYS; i++)
            assertEquals(iter, vals.get(i));
    }
}
 
Example 13
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 14
Source File: GridNearCacheStoreUpdateTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
     * @param txConc Transaction concurrency.
     * @param txIsolation Transaction isolation.
     * @throws Exception If fail.
     */
    private void checkNearBatchConcurrent(TransactionConcurrency txConc, TransactionIsolation txIsolation)
        throws Exception {
        final Map<String, String> data1 = new TreeMap<>();
        final Map<String, String> data2 = new TreeMap<>();

        for (int j = 0; j < 10; j++) {
            data1.clear();
            data2.clear();

            for (int i = j * 10; i < j * 10 + 10; i++) {
                data1.put(String.valueOf(i), String.valueOf(i));
                data2.put(String.valueOf(i), "other");
            }

            final IgniteCache<String, String> clientCache = this.cache;
            final IgniteCache<String, String> srvCache = srv.cache(CACHE_NAME);

            boolean tx = txConc != null && txIsolation != null;

            final CountDownLatch latch = new CountDownLatch(1);

            final IgniteInternalFuture<Object> fut1 = GridTestUtils.runAsync(new Callable<Object>() {
                @Override public Object call() throws Exception {
                    latch.await();

                    clientCache.getAll(data1.keySet());

                    return null;
                }
            });

            IgniteInternalFuture<Object> fut2 = GridTestUtils.runAsync(new Callable<Object>() {
                @Override public Object call() throws Exception {
                    latch.await();

                    srvCache.putAll(data2);

                    return null;
                }
            });

//            IgniteInternalFuture<Object> fut3 = null;
//
//            // TODO Sometimes Near cache becomes inconsistent
//            if (!tx) {
//                // TODO: IGNITE-3498
//                // TODO: Doesn't work on transactional cache.
//                fut3 = GridTestUtils.runAsync(new Callable<Object>() {
//                    @Override public Object call() throws Exception {
//                        latch.await();
//
//                        srvCache.removeAll(data1.keySet());
//
//                        return null;
//                    }
//                });
//            }

            latch.countDown();

//            if (!tx)
//                fut3.get();

            fut1.get();
            fut2.get();

            final Map<String, String> srvVals = srvCache.getAll(data1.keySet());
            final Map<String, String> clientVals = clientCache.getAll(data1.keySet());

            assertEquals(srvVals, clientVals);
        }
    }
 
Example 15
Source File: BulkReadWorker.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override protected void process(IgniteCache cache, Map entries) {
    cache.getAll(entries.keySet());
}
 
Example 16
Source File: IgniteCacheGroupsTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param cache Cache.
 */
private void cachePutAllGetAllContainsAll(IgniteCache cache) {
    int keys = 100;

    Map<Integer, Integer> data = generateDataMap(keys);

    cache.putAll(data);

    Map data0 = cache.getAll(data.keySet());

    assertEquals(data.size(), data0.size());

    for (Map.Entry<Integer, Integer> entry : data.entrySet())
        assertEquals(entry.getValue(), data0.get(entry.getKey()));

    assertTrue(cache.containsKeys(data.keySet()));

    tearDown(cache);
}
 
Example 17
Source File: IgnitePutGetBatchBenchmark.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
    IgniteCache<Integer, Object> cache = cacheForOperation();

    Set<Integer> keys = new TreeSet<>();

    while (keys.size() < args.batch())
        keys.add(nextRandom(args.range()));

    Map<Integer, Object> vals = cache.getAll(keys);

    Map<Integer, SampleValue> updates = new TreeMap<>();

    for (Integer key : keys) {
        Object val = vals.get(key);

        if (val != null)
            key = nextRandom(args.range());

        updates.put(key, new SampleValue(key));
    }

    cache.putAll(updates);

    return true;
}
 
Example 18
Source File: IgniteGetAllBenchmark.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
    Set<Integer> keys = U.newHashSet(args.batch());

    while (keys.size() < args.batch()) {
        int key = nextRandom(args.range());

        keys.add(key);
    }

    IgniteCache<Integer, Object> cache = cacheForOperation();

    cache.getAll(keys);

    return true;
}
 
Example 19
Source File: IgniteGetAllTxBenchmark.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
    Set<Integer> keys = U.newHashSet(args.batch());

    while (keys.size() < args.batch()) {
        int key = nextRandom(args.range());

        keys.add(key);
    }

    IgniteCache<Integer, Object> cache = cacheForOperation();

    cache.getAll(keys);

    return true;
}
 
Example 20
Source File: IgniteCacheReadFromBackupTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * @param nodes Number of nodes.
 * @param ccfg Cache configuration.
 * @throws Exception If failed.
 */
private void checkLocalRead(int nodes, CacheConfiguration<Object, Object> ccfg) throws Exception {
    for (int i = 0; i < nodes; i++) {
        Ignite ignite = ignite(i);

        log.info("Check node: " + ignite.name());

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

        List<Integer> backupKeys = backupKeys(cache, 2, 0);

        Integer backupKey = backupKeys.get(0);

        Integer nearKey = ccfg.getCacheMode() == PARTITIONED ? nearKey(cache) : null;

        checkLocalRead(ignite, ccfg, backupKey, nearKey);

        Set<Integer> keys = new HashSet<>(backupKeys);

        Map<Integer, Integer> vals = cache.getAll(keys);

        for (Integer key : keys)
            assertNull(vals.get(key));

        TestRecordingCommunicationSpi spi =
            (TestRecordingCommunicationSpi)ignite.configuration().getCommunicationSpi();

        List<Object> msgs = spi.recordedMessages(false);

        assertEquals(0, msgs.size());
    }
}