Java Code Examples for org.apache.ignite.Ignite#getOrCreateCache()

The following examples show how to use org.apache.ignite.Ignite#getOrCreateCache() . 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: PutElementstoOffHeap.java    From ignite-book-code-samples with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception{
    if(args.length <= 0){
        System.out.println("Usages! java -jar .\\target\\chapter-three-offheap-1.0-SNAPSHOT.one-jar.jar spring-offheap-tiered.xml");
        System.exit(0);
    }
    String springCoreFile = args[0];
    // Start Ignite cluster
    Ignite ignite = Ignition.start(springCoreFile);
    // get or create cache
    IgniteCache<Integer, String> cache =  ignite.getOrCreateCache("offheap-cache");
    for(int i = 1; i <= 1000; i++){
        cache.put(i, Integer.toString(i));
    }
    for(int i =1; i<=1000;i++){
        System.out.println("Cache get:"+ cache.get(i));
    }
    System.out.println("Wait 10 seconds for statistics");
    Thread.sleep(10000);
    // statistics
    System.out.println("Cache Hits:"+ cache.metrics(ignite.cluster()).getCacheHits());

    System.out.println("Enter crtl-x to quite the application!!!");
    Thread.sleep(Integer.MAX_VALUE); // sleep for 20 seconds

    ignite.close();
}
 
Example 2
Source File: CacheMvccStreamingInsertTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
    super.beforeTest();

    Ignite ignite = startGrid(0);
    sqlNexus = ignite.getOrCreateCache(new CacheConfiguration<>("sqlNexus").setSqlSchema("PUBLIC"));
    sqlNexus.query(q("" +
        "create table person(" +
        "  id int not null primary key," +
        "  name varchar not null" +
        ") with \"atomicity=transactional_snapshot\""
    ));

    Properties props = new Properties();
    props.setProperty(IgniteJdbcDriver.PROP_STREAMING, "true");
    conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1", props);
}
 
Example 3
Source File: FoldersReuseCompatibilityTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void apply(Ignite ignite) {
    ignite.active(true);

    final IgniteCache<Object, Object> cache = ignite.getOrCreateCache(CACHE_NAME);
    cache.put(KEY, VAL);
    cache.put("1", "2");
    cache.put(1, 2);
    cache.put(1L, 2L);
    cache.put(PersistenceBasicCompatibilityTest.TestEnum.A, "Enum_As_Key");
    cache.put("Enum_As_Value", PersistenceBasicCompatibilityTest.TestEnum.B);
    cache.put(PersistenceBasicCompatibilityTest.TestEnum.C, PersistenceBasicCompatibilityTest.TestEnum.C);

    cache.put("Serializable", new PersistenceBasicCompatibilityTest.TestSerializable(42));
    cache.put(new PersistenceBasicCompatibilityTest.TestSerializable(42), "Serializable_As_Key");
    cache.put("Externalizable", new PersistenceBasicCompatibilityTest.TestExternalizable(42));
    cache.put(new PersistenceBasicCompatibilityTest.TestExternalizable(42), "Externalizable_As_Key");
    cache.put(KEY_OBJ, new PersistenceBasicCompatibilityTest.TestStringContainerToBePrinted(VAL));

}
 
Example 4
Source File: IgniteCacheContainsKeyAtomicTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param all Check for set of keys.
 * @throws Exception If failed.
 */
private void checkPutIfAbsent(final boolean all) throws Exception {
    Ignite srv = ignite(0);

    final IgniteCache<Integer, Integer> cache1 = srv.getOrCreateCache(replicatedCache());
    final IgniteCache<Integer, Integer> cache2 = ignite(1).getOrCreateCache(replicatedCache());

    final AtomicInteger fails = new AtomicInteger(0);

    GridTestUtils.runMultiThreaded(new Runnable() {
        @Override public void run() {
            for (int i = 0; i < 100; i++) {
                if (!cache1.putIfAbsent(i, i)) {
                    if (all ? !cache2.containsKeys(Collections.singleton(i)) : !cache2.containsKey(i))
                        fails.incrementAndGet();
                }
            }
        }
    }, 100, "put-if-abs");

    assertEquals(0, fails.get());
}
 
Example 5
Source File: IgniteExpiryExample.java    From ignite-book-code-samples with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) {
    // Start Ignite cluster
    Ignite ignite = Ignition.start("default-config.xml");

    // get or create cache
    IgniteCache<Integer, Person> cache =  ignite.getOrCreateCache("testCache");
    Person p1 = new Person(37, "Shamim");
    Person p2 = new Person(2, "Mishel");
    Person p3 = new Person(55, "scott");
    Person p4 = new Person(5, "Tiger");

    cache.put(1, p1);
    cache.put(2, p2);
    cache.put(3, p3);
    cache.put(4, p4);

    System.out.println("Enter crtl-x to quite the application!!!");

}
 
Example 6
Source File: JavaIgniteDataFrameWriteExample.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** */
private static void setupServerAndData(Ignite ignite) {
    //Creating first test cache.
    CacheConfiguration<?, ?> ccfg = new CacheConfiguration<>(CACHE_NAME).setSqlSchema("PUBLIC");

    IgniteCache<?, ?> cache = ignite.getOrCreateCache(ccfg);

    //Creating SQL table.
    cache.query(new SqlFieldsQuery(
            "CREATE TABLE person (id LONG, name VARCHAR, city_id LONG, PRIMARY KEY (id)) " +
                    "WITH \"backups=1\"")).getAll();

    cache.query(new SqlFieldsQuery("CREATE INDEX on Person (city_id)")).getAll();

    //Inserting some data to tables.
    SqlFieldsQuery qry = new SqlFieldsQuery("INSERT INTO person (id, name, city_id) values (?, ?, ?)");

    cache.query(qry.setArgs(1L, "John Doe", 3L)).getAll();
    cache.query(qry.setArgs(2L, "Jane Roe", 2L)).getAll();
    cache.query(qry.setArgs(3L, "Mary Major", 1L)).getAll();
    cache.query(qry.setArgs(4L, "Richard Miles", 2L)).getAll();
}
 
Example 7
Source File: IgniteCacheCreatePutMultiNodeSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param grid Grid.
 * @param cacheName Cache name.
 * @return Cache.
 */
private IgniteCache<Integer, Integer> getCache(Ignite grid, String cacheName) {
    CacheConfiguration<Integer, Integer> ccfg = new CacheConfiguration<>(cacheName);

    ccfg.setCacheMode(CacheMode.PARTITIONED);
    ccfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);
    ccfg.setBackups(1);
    ccfg.setNearConfiguration(null);

    return grid.getOrCreateCache(ccfg);
}
 
Example 8
Source File: TxDeadlockDetectionUnmasrhalErrorsTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param ignite Ignite.
 * @param name Name.
 */
private IgniteCache<Integer, Integer> getCache(Ignite ignite, String name) {
    CacheConfiguration ccfg = defaultCacheConfiguration();

    ccfg.setName(name);
    ccfg.setCacheMode(CacheMode.PARTITIONED);
    ccfg.setBackups(0);
    ccfg.setNearConfiguration(null);

    return ignite.getOrCreateCache(ccfg);
}
 
Example 9
Source File: TcpClientDiscoverySpiCoordinatorChangeTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that a client node doesn't fail because of coordinator change.
 *
 * @throws Exception If test fails.
 */
@Test
public void testClientNotFailed() throws Exception {
    TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);

    // Start server A.
    Ignite srvA = startNode("server-a", ipFinder, false);

    // Start the client.
    Ignite client = startNode("client", ipFinder, true);

    AtomicBoolean clientReconnectState = getClientReconnectState(client);

    // Start server B.
    Ignite srvB = startNode("server-b", ipFinder, false);

    // Stop server A.
    srvA.close();

    // Will throw an exception if the client is disconnected.
    client.getOrCreateCache("CACHE-NAME");

    // Check that the client didn't disconnect/reconnect quickly.
    assertFalse("Client node was failed and reconnected to the cluster.", clientReconnectState.get());

    // Stop the client.
    client.close();

    // Stop server B.
    srvB.close();
}
 
Example 10
Source File: IgniteBaselineAffinityTopologyActivationTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
private void createAndFillCache(Ignite srv) {
    IgniteCache cache = srv.getOrCreateCache(cacheConfiguration());

    for (int i = 0; i < ENTRIES_COUNT; i++)
        cache.put(i, new TestValue(i, "str" + i));
}
 
Example 11
Source File: TcpDiscoveryMetricsWarnLogTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and fills cahes with test data.
 *
 * @param cacheNum Cache number to generate a cache name.
 * @param ignite Ignite instance to create a cache in.
 */
private void createAndFillCache(int cacheNum, Ignite ignite) {
    IgniteCache<Object, Object> cache = ignite.getOrCreateCache(
        new CacheConfiguration<>(DEFAULT_CACHE_NAME + cacheNum).setStatisticsEnabled(true)
    );

    for (int i = 1; i < 100; i++)
        cache.put(i, i);
}
 
Example 12
Source File: GridCacheAtomicStampedApiSelfAbstractTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testIsolation() throws Exception {
    Ignite ignite = grid(0);

    CacheConfiguration cfg = new CacheConfiguration(DEFAULT_CACHE_NAME);

    cfg.setName("MyCache");
    cfg.setAtomicityMode(TRANSACTIONAL);
    cfg.setWriteSynchronizationMode(FULL_SYNC);

    IgniteCache<Integer, Integer> cache = ignite.getOrCreateCache(cfg);

    try {
        String atomicName = UUID.randomUUID().toString();

        String initVal = "qwerty";
        String initStamp = "asdf";

        IgniteAtomicStamped<String, String> atomicStamped = ignite.atomicStamped(atomicName,
            initVal,
            initStamp,
            true);

        try (Transaction tx = ignite.transactions().txStart()) {
            cache.put(1,1);

            assertEquals(initVal, atomicStamped.value());
            assertEquals(initStamp, atomicStamped.stamp());
            assertEquals(initVal, atomicStamped.get().get1());
            assertEquals(initStamp, atomicStamped.get().get2());

            assertTrue(atomicStamped.compareAndSet(initVal, "b", initStamp, "d"));

            tx.rollback();
        }

        assertEquals(0, cache.size());

        assertEquals("b", atomicStamped.value());
        assertEquals("d", atomicStamped.stamp());

        atomicStamped.close();

        assertTrue(atomicStamped.removed());
    }
    finally {
        ignite.destroyCache(cfg.getName());
    }
}
 
Example 13
Source File: CamelStreamerMediation.java    From ignite-book-code-samples with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws Exception{
    System.out.println("Camel Streamer Mediation ingestion!");
    Ignition.setClientMode(true);
    Ignite ignite = Ignition.start("example-ignite.xml");
    // Create a CamelContext with a custom route that will:
    //  (1) consume from our Jetty endpoint.
    //  (2) transform incoming JSON into a Java object with Jackson.
    //  (3) uses JSR 303 Bean Validation to validate the object.
    //  (4) dispatches to the direct:ignite.ingest endpoint, where the streamer is consuming from.
    // camel_cache cache configuration
    CacheConfiguration<String, String> camel_cache_cfg = new CacheConfiguration<>("camel-direct");

    camel_cache_cfg.setIndexedTypes(String.class, String.class);

    IgniteCache<String, String> camel_cache = ignite.getOrCreateCache(camel_cache_cfg);
    // Create an streamer pipe which ingests into the 'camel_cache' cache.
    IgniteDataStreamer<String, String> pipe = ignite.dataStreamer(camel_cache.getName());
    // does the tricks
    pipe.autoFlushFrequency(1l);
    pipe.allowOverwrite(true);
    // Create a Camel streamer and connect it.
    CamelStreamer<String, String> streamer = new CamelStreamer<>();
    streamer.setIgnite(ignite);
    streamer.setStreamer(pipe);
    streamer.setEndpointUri("direct:ignite.ingest");
    CamelContext context = new DefaultCamelContext();
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("jetty:http://127.0.0.1:8081/ignite?httpMethodRestrict=POST")
                    .unmarshal().json(JsonLibrary.Jackson)
                    .to("bean-validator:validate")
                    .to("direct:ignite.ingest");
        }
    });

    // Remember our Streamer is now consuming from the Direct endpoint above.
    streamer.setCamelContext(context);
    streamer.setSingleTupleExtractor(new StreamSingleTupleExtractor<Exchange, String, String>() {
        @Override
        public Map.Entry<String, String> extract(Exchange exchange) {
            String stationId = exchange.getIn().getHeader("X-StationId", String.class);
            String temperature = exchange.getIn().getBody(String.class);
            System.out.println("StationId:" + stationId + " temperature:" + temperature);
            return new GridMapEntry<>(stationId, temperature);
        }
    });
    streamer.start();
    //streamer.start();
}
 
Example 14
Source File: CamelStreamerMediationIngestion.java    From ignite-book-code-samples with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("Camel Streamer Mediation ingestion!");
    Ignition.setClientMode(true);
    Ignite ignite = Ignition.start("example-ignite.xml");
    if (!ExamplesUtils.hasServerNodes(ignite))
        return;
    if (getFileLocation() == null || getFileLocation().isEmpty()){
        System.out.println("properties file is empty or null!");
        return;
    }
    // camel_cache cache configuration
    CacheConfiguration<String, String> camel_cache_cfg = new CacheConfiguration<>("camel-direct");

    camel_cache_cfg.setIndexedTypes(String.class, String.class);

    IgniteCache<String, String> camel_cache = ignite.getOrCreateCache(camel_cache_cfg);
    // Create an streamer pipe which ingests into the 'camel_cache' cache.
    IgniteDataStreamer<String, String> pipe = ignite.dataStreamer(camel_cache.getName());
    // does the tricks
    pipe.autoFlushFrequency(1l);
    pipe.allowOverwrite(true);
    // Create a Camel streamer and connect it.
    CamelStreamer<String, String> streamer = new CamelStreamer<>();
    streamer.setIgnite(ignite);
    streamer.setStreamer(pipe);
    streamer.setEndpointUri("direct:ignite.ingest");
    CamelContext context = new DefaultCamelContext();
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("file://"+getFileLocation())
                    .unmarshal().json(JsonLibrary.Jackson, MnpRouting.class)
                    .bean(new RouteProcessor(), "process")
                    .to("direct:ignite.ingest");
        }
    });

    streamer.setCamelContext(context);
    streamer.setSingleTupleExtractor(new StreamSingleTupleExtractor<Exchange, String, String>() {
        @Override
        public Map.Entry<String, String> extract(Exchange exchange) {
            String key = exchange.getIn().getHeader("key", String.class);
            String routeMsg = exchange.getIn().getBody(String.class);
            return new GridMapEntry<>(key, routeMsg);

        }
    });
    streamer.start();
}
 
Example 15
Source File: P2PScanQueryUndeployTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param client ignite instance.
 * @param predCls loaded predicate class.
 * @throws Exception if failed.
 */
private void invokeScanQueryAndStopClient(Ignite client, Class predCls) throws Exception {
    IgniteCache<Integer, String> cache = client.getOrCreateCache(CACHE_NAME);

    assertEquals("Invalid number of sent grid deployment requests", 0, MessageCountingCommunicationSpi.deploymentRequestCount());

    assertFalse(PREDICATE_CLASSNAME + " mustn't be cached! ", igniteUtilsCachedClasses().contains(PREDICATE_CLASSNAME));

    cache.query(new ScanQuery<>((IgniteBiPredicate<Integer, String>)predCls.newInstance())).getAll();

    // first request is GridDeployment.java 716 and second is GridDeployment.java 501
    assertEquals("Invalid number of sent grid deployment requests", 2, MessageCountingCommunicationSpi.deploymentRequestCount());

    assertTrue(PREDICATE_CLASSNAME + " must be cached! ", igniteUtilsCachedClasses().contains(PREDICATE_CLASSNAME));

    client.close();

    assertFalse(PREDICATE_CLASSNAME + " mustn't be cached! ", igniteUtilsCachedClasses().contains(PREDICATE_CLASSNAME));
}
 
Example 16
Source File: WalModeChangeAdvancedSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Test coordinator node migration.
 *
 * @param failCrd Whether to fail coordinator nodes.
 * @throws Exception If failed.
 */
public void checkNodeRestart(boolean failCrd) throws Exception {
    startGrid(config(SRV_1, false, false));
    startGrid(config(SRV_2, false, false));

    Ignite cli = startGrid(config(CLI, true, false));

    cli.cluster().active(true);

    cli.getOrCreateCache(cacheConfig(PARTITIONED));

    final AtomicInteger restartCnt = new AtomicInteger();

    final int restarts = SF.applyLB(10, 3);

    Thread t = new Thread(new Runnable() {
        @Override public void run() {
            boolean firstOrSecond = true;

            while (restartCnt.get() < restarts) {
                String victimName;

                if (failCrd) {
                    victimName = firstOrSecond ? SRV_1 : SRV_2;

                    firstOrSecond = !firstOrSecond;
                }
                else
                    victimName = SRV_2;

                try {
                    stopGrid(victimName);
                    startGrid(config(victimName, false, false));

                    Thread.sleep(500);
                }
                catch (Exception e) {
                    throw new RuntimeException();
                }

                restartCnt.incrementAndGet();

                log.info(">>> Finished restart: " + restartCnt.get());
            }
        }
    });

    t.start();

    boolean state = true;

    while (restartCnt.get() < restarts && !Thread.currentThread().isInterrupted()) {
        try {
            if (state)
                cli.cluster().disableWal(CACHE_NAME);
            else
                cli.cluster().enableWal(CACHE_NAME);

            state = !state;
        }
        catch (IgniteException ignore) {
            // Possible disconnect, re-try.
        }
    }
}
 
Example 17
Source File: DataStreamerImplSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testClientEventsNotCausingRemaps() throws Exception {
    Ignite ignite = startGrids(2);

    ignite.getOrCreateCache(DEFAULT_CACHE_NAME);

    IgniteDataStreamer<Object, Object> streamer = ignite.dataStreamer(DEFAULT_CACHE_NAME);

    ((DataStreamerImpl)streamer).maxRemapCount(3);

    streamer.addData(1, 1);

    for (int topChanges = 0; topChanges < 30; topChanges++) {
        IgniteEx node = startClientGrid(getConfiguration("flapping-client"));

        streamer.addData(1, 1);

        node.close();

        streamer.addData(1, 1);
    }

    streamer.flush();
    streamer.close();
}
 
Example 18
Source File: IgniteAbsentEvictionNodeOutOfBaselineTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * Removed partitions if node is out of baseline.
 */
@Test
public void testPartitionsRemovedIfJoiningNodeNotInBaseline() throws Exception {
    //given: start 3 nodes with data
    Ignite ignite0 = startGrids(3);

    ignite0.cluster().baselineAutoAdjustEnabled(false);
    ignite0.cluster().active(true);

    IgniteCache<Object, Object> cache = ignite0.getOrCreateCache(TEST_CACHE_NAME);

    for (int i = 0; i < 100; i++)
        cache.put(i, i);

    //when: stop one node and reset baseline topology
    stopGrid(2);

    resetBaselineTopology();

    ignite0.resetLostPartitions(Collections.singleton(TEST_CACHE_NAME));

    awaitPartitionMapExchange();

    for (int i = 0; i < 200; i++)
        cache.put(i, i);

    //then: after returning stopped node to grid its partitions should be removed
    IgniteEx ignite2 = startGrid(2);

    List<GridDhtLocalPartition> partitions = ignite2.cachex(TEST_CACHE_NAME).context().topology().localPartitions();

    assertTrue("Should be empty : " + partitions, partitions.isEmpty());
}
 
Example 19
Source File: GridMarshallerMappingConsistencyTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * Make a value be rebalanced to a node after the mapping was accepted.
 * Check, that the mapping is available after restart.
 *
 * @throws Exception If failed.
 */
@Test
public void testMappingsPersistedOnJoin() throws Exception {
    Ignite g1 = startGrid(1);
    Ignite g2 = startGrid(2);

    g1.cluster().active(true);

    CacheConfiguration<Integer, DummyObject> cacheCfg = new CacheConfiguration<>(CACHE_NAME);
    cacheCfg.setBackups(1);

    IgniteCache<Integer, DummyObject> c1 = g1.getOrCreateCache(cacheCfg);
    IgniteCache<Integer, DummyObject> c2 = g2.getOrCreateCache(cacheCfg);

    int k = primaryKey(c2);

    stopGrid(2);

    c1.put(k, new DummyObject(k));

    startGrid(2);

    awaitPartitionMapExchange();

    stopAllGrids();

    g2 = startGrid(2);

    g2.cluster().active(true);

    c2 = g2.cache(CACHE_NAME);

    assertEquals(k, c2.get(k).val);
}
 
Example 20
Source File: CacheClientsConcurrentStartTest.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * @param grid Grid.
 * @return Cache.
 */
private IgniteCache getCache(Ignite grid, String cacheName) {
    return grid.getOrCreateCache(cacheConfiguration(cacheName));
}