Java Code Examples for org.apache.ignite.Ignition#ignite()

The following examples show how to use org.apache.ignite.Ignition#ignite() . 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: SpringCacheManager.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void onApplicationEvent(ContextRefreshedEvent event) {
    if (ignite == null) {

        if (cfgPath != null && cfg != null) {
            throw new IllegalArgumentException("Both 'configurationPath' and 'configuration' are " +
                "provided. Set only one of these properties if you need to start a Ignite node inside of " +
                "SpringCacheManager. If you already have a node running, omit both of them and set" +
                "'igniteInstanceName' property.");
        }

        try {
            if (cfgPath != null) {
                ignite = IgniteSpring.start(cfgPath, springCtx);
            }
            else if (cfg != null)
                ignite = IgniteSpring.start(cfg, springCtx);
            else
                ignite = Ignition.ignite(igniteInstanceName);
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }
}
 
Example 2
Source File: EventsExample.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Listen to events that happen only on local node.
 *
 * @throws IgniteException If failed.
 */
private static void localListen() throws IgniteException {
    System.out.println();
    System.out.println(">>> Local event listener example.");

    Ignite ignite = Ignition.ignite();

    IgnitePredicate<TaskEvent> lsnr = evt -> {
        System.out.println("Received task event [evt=" + evt.name() + ", taskName=" + evt.taskName() + ']');

        return true; // Return true to continue listening.
    };

    // Register event listener for all local task execution events.
    ignite.events().localListen(lsnr, EVTS_TASK_EXECUTION);

    // Generate task events.
    ignite.compute().withName("example-event-task").run(() -> System.out.println("Executing sample job."));

    // Unsubscribe local task event listener.
    ignite.events().stopLocalListen(lsnr);
}
 
Example 3
Source File: CacheAffinityExample.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Collocates jobs with keys they need to work on using
 * {@link IgniteCompute#affinityRun(String, Object, IgniteRunnable)} method.
 */
private static void visitUsingAffinityRun() {
    Ignite ignite = Ignition.ignite();

    final IgniteCache<Integer, String> cache = ignite.cache(CACHE_NAME);

    for (int i = 0; i < KEY_CNT; i++) {
        int key = i;

        // This runnable will execute on the remote node where
        // data with the given key is located. Since it will be co-located
        // we can use local 'peek' operation safely.
        ignite.compute().affinityRun(CACHE_NAME, key,
            () -> System.out.println("Co-located using affinityRun [key= " + key + ", value=" + cache.localPeek(key) + ']'));
    }
}
 
Example 4
Source File: JavaStandaloneIgniteRDDSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testStoreDataToIgnite() throws Exception {
    JavaSparkContext sc = new JavaSparkContext("local[*]", "test");

    try {
        JavaIgniteContext<String, String> ic = new JavaIgniteContext<>(sc, new IgniteConfigProvider());

        ic.fromCache(ENTITY_CACHE_NAME)
            .savePairs(sc.parallelize(F.range(0, KEYS_CNT), 2).mapToPair(TO_PAIR_F));

        Ignite ignite = Ignition.ignite("grid-0");

        IgniteCache<String, String> cache = ignite.cache(ENTITY_CACHE_NAME);

        for (int i = 0; i < KEYS_CNT; i++) {
            String val = cache.get(String.valueOf(i));

            assertNotNull("Value was not put to cache for key: " + i, val);
            assertEquals("Invalid value stored for key: " + i, "val" + i, val);
        }
    }
    finally {
        sc.stop();
    }
}
 
Example 5
Source File: JavaStandaloneIgniteRDDSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testStoreDataToIgnite() throws Exception {
    JavaSparkContext sc = new JavaSparkContext("local[*]", "test");

    try {
        JavaIgniteContext<String, String> ic = new JavaIgniteContext<>(sc, new IgniteConfigProvider());

        ic.fromCache(ENTITY_CACHE_NAME)
            .savePairs(sc.parallelize(F.range(0, KEYS_CNT), 2).mapToPair(TO_PAIR_F));

        Ignite ignite = Ignition.ignite("grid-0");

        IgniteCache<String, String> cache = ignite.cache(ENTITY_CACHE_NAME);

        for (int i = 0; i < KEYS_CNT; i++) {
            String val = cache.get(String.valueOf(i));

            assertNotNull("Value was not put to cache for key: " + i, val);
            assertEquals("Invalid value stored for key: " + i, "val" + i, val);
        }
    }
    finally {
        sc.stop();
    }
}
 
Example 6
Source File: SpringTransactionManager.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public void onApplicationEvent(ContextRefreshedEvent event) {
    if (ignite == null) {
        if (cfgPath != null && cfg != null) {
            throw new IllegalArgumentException("Both 'configurationPath' and 'configuration' are " +
                "provided. Set only one of these properties if you need to start a Ignite node inside of " +
                "SpringCacheManager. If you already have a node running, omit both of them and set" +
                "'igniteInstanceName' property.");
        }

        try {
            if (cfgPath != null) {
                ignite = IgniteSpring.start(cfgPath, springCtx);
            }
            else if (cfg != null)
                ignite = IgniteSpring.start(cfg, springCtx);
            else
                ignite = Ignition.ignite(igniteInstanceName);
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    if (transactionConcurrency == null)
        transactionConcurrency = ignite.configuration().getTransactionConfiguration().getDefaultTxConcurrency();

    log = ignite.log();
}
 
Example 7
Source File: CacheAffinityExample.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Collocates jobs with keys they need to work on using {@link Affinity#mapKeysToNodes(Collection)}
 * method. The difference from {@code affinityRun(...)} method is that here we process multiple keys
 * in a single job.
 */
private static void visitUsingMapKeysToNodes() {
    final Ignite ignite = Ignition.ignite();

    Collection<Integer> keys = new ArrayList<>(KEY_CNT);

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

    // Map all keys to nodes.
    Map<ClusterNode, Collection<Integer>> mappings = ignite.<Integer>affinity(CACHE_NAME).mapKeysToNodes(keys);

    for (Map.Entry<ClusterNode, Collection<Integer>> mapping : mappings.entrySet()) {
        ClusterNode node = mapping.getKey();

        final Collection<Integer> mappedKeys = mapping.getValue();

        if (node != null) {
            // Bring computations to the nodes where the data resides (i.e. collocation).
            ignite.compute(ignite.cluster().forNode(node)).run(() -> {
                IgniteCache<Integer, String> cache = ignite.cache(CACHE_NAME);

                // Peek is a local memory lookup, however, value should never be 'null'
                // as we are co-located with node that has a given key.
                for (Integer key : mappedKeys)
                    System.out.println("Co-located using mapKeysToNodes [key= " + key +
                        ", value=" + cache.localPeek(key) + ']');
            });
        }
    }
}
 
Example 8
Source File: JavaStandaloneIgniteRDDSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testReadDataFromIgnite() throws Exception {
    JavaSparkContext sc = new JavaSparkContext("local[*]", "test");

    try {
        JavaIgniteContext<String, Integer> ic = new JavaIgniteContext<>(sc, new IgniteConfigProvider());

        Ignite ignite = Ignition.ignite("grid-0");

        IgniteCache<String, Integer> cache = ignite.cache(ENTITY_CACHE_NAME);

        for (int i = 0; i < KEYS_CNT; i++)
            cache.put(String.valueOf(i), i);

        JavaRDD<Integer> values = ic.fromCache(ENTITY_CACHE_NAME).map(STR_INT_PAIR_TO_INT_F);

        int sum = values.fold(0, SUM_F);

        int expSum = (KEYS_CNT * KEYS_CNT + KEYS_CNT) / 2 - KEYS_CNT;

        assertEquals(expSum, sum);
    }
    finally {
        sc.stop();
    }
}
 
Example 9
Source File: GridLifecycleBeanSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testGetIgnite() throws Exception {
    final AtomicBoolean done = new AtomicBoolean();

    bean = new LifeCycleBaseBean() {
        /** */
        @IgniteInstanceResource
        private Ignite ignite;

        @Override public void onLifecycleEvent(LifecycleEventType evt) {
            super.onLifecycleEvent(evt);

            if (evt == LifecycleEventType.AFTER_NODE_START) {
                Ignite ignite0 = Ignition.ignite(ignite.name());

                assertNotNull(ignite0);
                assertNotNull(ignite0.cluster().localNode());

                done.set(true);
            }
        }
    };

    try {
        startGrid();

        assertTrue(done.get());
    }
    finally {
        stopAllGrids();
    }
}
 
Example 10
Source File: IgnitionComponentProxyTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 *
 */
@Test
public void testIgniteWithID() {
    final UUID srvId = grid(SRV).localNode().id();

    Supplier<Ignite> s = new Supplier<Ignite>() {
        @Override public Ignite get() {
            return Ignition.ignite(srvId);
        }
    };

    check(s);
}
 
Example 11
Source File: IgnitionComponentProxyTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 *
 */
@Test
public void testIgniteWithName() {
    Supplier<Ignite> s = new Supplier<Ignite>() {
        @Override public Ignite get() {
            return Ignition.ignite(SRV);
        }
    };

    check(s);
}
 
Example 12
Source File: JavaStandaloneIgniteRDDSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testReadDataFromIgnite() throws Exception {
    JavaSparkContext sc = new JavaSparkContext("local[*]", "test");

    try {
        JavaIgniteContext<String, Integer> ic = new JavaIgniteContext<>(sc, new IgniteConfigProvider());

        Ignite ignite = Ignition.ignite("grid-0");

        IgniteCache<String, Integer> cache = ignite.cache(ENTITY_CACHE_NAME);

        for (int i = 0; i < KEYS_CNT; i++)
            cache.put(String.valueOf(i), i);

        JavaRDD<Integer> values = ic.fromCache(ENTITY_CACHE_NAME).map(STR_INT_PAIR_TO_INT_F);

        int sum = values.fold(0, SUM_F);

        int expSum = (KEYS_CNT * KEYS_CNT + KEYS_CNT) / 2 - KEYS_CNT;

        assertEquals(expSum, sum);
    }
    finally {
        sc.stop();
    }
}
 
Example 13
Source File: IgniteRepositoryFactory.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
private Ignite igniteForRepoConfig(RepositoryConfig config) {
    try {
        String igniteInstanceName = evaluateExpression(config.igniteInstance());
        return (Ignite)ctx.getBean(igniteInstanceName);
    }
    catch (BeansException ex) {
        try {
            String igniteConfigName = evaluateExpression(config.igniteCfg());
            IgniteConfiguration cfg = (IgniteConfiguration)ctx.getBean(igniteConfigName);
            try {
                // first try to attach to existing ignite instance
                return Ignition.ignite(cfg.getIgniteInstanceName());
            }
            catch (Exception ignored) {
                // nop
            }
            return Ignition.start(cfg);
        }
        catch (BeansException ex2) {
            try {
                String igniteSpringCfgPath = evaluateExpression(config.igniteSpringCfgPath());
                String path = (String)ctx.getBean(igniteSpringCfgPath);
                return Ignition.start(path);
            }
            catch (BeansException ex3) {
                throw new IgniteException("Failed to initialize Ignite repository factory. Ignite instance or"
                    + " IgniteConfiguration or a path to Ignite's spring XML "
                    + "configuration must be defined in the"
                    + " application configuration");
            }
        }
    }
}
 
Example 14
Source File: IgniteRepositoryFactory.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
private Ignite igniteForRepoConfig(RepositoryConfig config) {
    try {
        String igniteInstanceName = evaluateExpression(config.igniteInstance());
        return (Ignite)ctx.getBean(igniteInstanceName);
    }
    catch (BeansException ex) {
        try {
            String igniteConfigName = evaluateExpression(config.igniteCfg());
            IgniteConfiguration cfg = (IgniteConfiguration)ctx.getBean(igniteConfigName);
            try {
                // first try to attach to existing ignite instance
                return Ignition.ignite(cfg.getIgniteInstanceName());
            }
            catch (Exception ignored) {
                // nop
            }
            return Ignition.start(cfg);
        }
        catch (BeansException ex2) {
            try {
                String igniteSpringCfgPath = evaluateExpression(config.igniteSpringCfgPath());
                String path = (String)ctx.getBean(igniteSpringCfgPath);
                return Ignition.start(path);
            }
            catch (BeansException ex3) {
                throw new IgniteException("Failed to initialize Ignite repository factory. Ignite instance or"
                    + " IgniteConfiguration or a path to Ignite's spring XML "
                    + "configuration must be defined in the"
                    + " application configuration");
            }
        }
    }
}
 
Example 15
Source File: GridAbstractTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public R call() throws Exception {
    Ignite ignite = Ignition.ignite(id);

    return job.call(ignite);
}
 
Example 16
Source File: HibernateAccessStrategyFactory.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param cfgValues {@link Map} of config values.
 */
public void start(Map<Object, Object> cfgValues) {
    cachePrefix = cfgValues.getOrDefault(CACHE_PREFIX, "").toString();

    verifyAtomicity = Boolean.valueOf(cfgValues.getOrDefault(VERIFY_ATOMICITY, verifyAtomicity).toString());

    Object gridCfg = cfgValues.get(GRID_CONFIG_PROPERTY);

    Object igniteInstanceName = cfgValues.get(IGNITE_INSTANCE_NAME_PROPERTY);

    if (gridCfg != null) {
        try {
            ignite = G.start(gridCfg.toString());
        }
        catch (IgniteException e) {
            throw eConverter.convert(e);
        }
    }
    else
        ignite = Ignition.ignite(igniteInstanceName == null ? null : igniteInstanceName.toString());

    for (Map.Entry entry : cfgValues.entrySet()) {
        String key = entry.getKey().toString();

        if (key.startsWith(REGION_CACHE_PROPERTY)) {
            String regionName = key.substring(REGION_CACHE_PROPERTY.length());

            String cacheName = entry.getValue().toString();

            if (((IgniteKernal) ignite).getCache(cachePrefix + cacheName) == null) {
                throw new IllegalArgumentException("Cache '" + cacheName + "' specified for region '" + regionName + "' " +
                    "is not configured.");
            }

            regionCaches.put(regionName, cacheName);
        }
    }

    IgniteLogger log = ignite.log().getLogger(getClass());

    if (log.isDebugEnabled())
        log.debug("HibernateRegionFactory started [igniteInstanceName=" + igniteInstanceName + ']');
}
 
Example 17
Source File: IgniteLockExample.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public void run() {
    System.out.println("Consumer started. ");

    Ignite g = Ignition.ignite();

    IgniteLock lock = g.reentrantLock(reentrantLockName, true, false, true);

    // Condition to wait on when queue is full.
    IgniteCondition notFull = lock.getOrCreateCondition(NOT_FULL);

    // Signaled to wait on when queue is empty.
    IgniteCondition notEmpty = lock.getOrCreateCondition(NOT_EMPTY);

    // Signaled when job is done.
    IgniteCondition done = lock.getOrCreateCondition(SYNC_NAME);

    IgniteCache<String, Integer> cache = g.cache(CACHE_NAME);

    for (int i = 0; i < OPS_COUNT; i++) {
        try {
            lock.lock();

            int val = cache.get(QUEUE_ID);

            while (val <= 0) {
                System.out.println("Queue is empty. Consumer [nodeId=" +
                    Ignition.ignite().cluster().localNode().id() + " paused.");

                notEmpty.await();

                val = cache.get(QUEUE_ID);
            }

            val--;

            System.out.println("Consumer [nodeId=" + Ignition.ignite().cluster().localNode().id() +
                ", available=" + val + ']');

            cache.put(QUEUE_ID, val);

            notFull.signalAll();
        }
        finally {
            lock.unlock();
        }
    }

    System.out.println("Consumer finished [nodeId=" + Ignition.ignite().cluster().localNode().id() + ']');

    try {
        lock.lock();

        int count = cache.get(SYNC_NAME);

        count--;

        cache.put(SYNC_NAME, count);

        // Signals the master thread.
        done.signal();
    }
    finally {
        lock.unlock();
    }
}
 
Example 18
Source File: TestJtaTxServlet.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse res)
    throws ServletException, IOException {
    final int key1 = 1;
    final int key2 = 2;

    final String correctVal1 = "correct_val1";
    final String correctVal2 = "correct_val1";
    final String incorrectVal1 = "incorrect_val2";
    final String incorrectVal2 = "incorrect_val2";

    final PrintWriter writer = res.getWriter();

    try {
        final Ignite ignite = Ignition.ignite();

        final IgniteCache<Integer, String> cache = ignite.cache("tx");

        TransactionManager tmMgr = TransactionManagerFactory.getTransactionManager();

        tmMgr.begin();

        cache.put(key1, correctVal1);
        cache.put(key2, correctVal2);

        writer.println("Transaction #1. Put values [key1=" + key1 + ", val1=" + cache.get(key1)
            + ", key2=" + key2 + ", val2=" + cache.get(key2) + "]");
        writer.println();

        tmMgr.commit();

        try {
            tmMgr.begin();

            writer.println("Transaction #2. Current values [key1=" + key1 + ", val1=" + cache.get(key1)
                + ", key2=" + key2 + ", val2=" + cache.get(key2) + "]");

            cache.put(key1, incorrectVal1);
            cache.put(key2, incorrectVal2);

            writer.println("Transaction #2. Put values [key1=" + key1 + ", val1=" + cache.get(key1)
                + ", key2=" + key2 + ", val2=" + cache.get(key2) + "]");

            tmMgr.setRollbackOnly();

            tmMgr.commit();
        }
        catch (final RollbackException ignored) {
            writer.println("Transaction #2. setRollbackOnly [key1=" + key1 + ", val1=" + cache.get(key1)
                + ", key2=" + key2 + ", val2=" + cache.get(key2) + "]");
        }

        writer.println();

        tmMgr.begin();

        writer.println("Transaction #2. Current values [key1=" + key1 + ", val1=" + cache.get(key1)
            + ", key2=" + key2 + ", val2=" + cache.get(key2) + "]");

        tmMgr.commit();
    }
    catch (final Throwable e) {
        e.printStackTrace(writer);
    }
}
 
Example 19
Source File: IgniteCacheExample.java    From tutorials with MIT License 3 votes vote down vote up
public static void main(String[] args) {

        Ignite ignite = Ignition.ignite();

        IgniteCache<Integer, String> cache = ignite.cache("baeldungCache");

        cache.put(1, "baeldung cache value");

        String message = cache.get(1);
    }
 
Example 20
Source File: IgniteApp.java    From tutorials with MIT License 3 votes vote down vote up
private void getUsingTheCache(Integer employeeId) {

        Ignite ignite = Ignition.ignite();

        IgniteCache<Integer, EmployeeDTO> cache = ignite.cache("baeldungCache");

        EmployeeDTO employeeDTO = cache.get(employeeId);

        System.out.println(employeeDTO);

        SqlFieldsQuery sql = new SqlFieldsQuery(
                "select * from EmployeeDTO where isEmployed = 'true'");

        QueryCursor<List<?>> cursor = cache.query(sql);
    }