Using Java to Operate Apache Ignite
Using Java to operate Apache Ignite can be done through Ignite's Java API. The following is an example code for data insertion, modification, query, and deletion using Apache Ignite.
Firstly, you need to add Apache Ignite's Maven dependency to the project. The following dependencies can be added to the pom.xml file of the project:
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-core</artifactId>
<version>2.10.0</version>
</dependency>
Next, create an Ignite instance and configure it. You can use the 'IgniteConfiguration' class to configure Ignite instances, such as setting cluster names and persistent storage paths.
import org.apache.ignite.Ignite;
import org.apache.ignite.Ignition;
import org.apache.ignite.configuration.IgniteConfiguration;
//Create Ignite instance
IgniteConfiguration cfg = new IgniteConfiguration();
cfg.setIgniteInstanceName("myIgniteInstance");
cfg.setPeerClassLoadingEnabled(true);
//Start Ignite instance
Ignite ignite = Ignition.start(cfg);
Data operation example:
1. Insert data:
//Obtain or create an Ignite cache
IgniteCache<Integer, String> cache = ignite.getOrCreateCache("myCache");
//Insert Data
cache.put(1, "John");
cache.put(2, "Jane");
2. Modify data:
//Update data
cache.replace(1, "John", "Jonathan");
3. Query data:
//Query data
String name = cache.get(1);
System.out.println(name);
4. Delete data:
//Delete data
cache.remove(1);
Complete example code:
import org.apache.ignite.Ignite;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
public class IgniteExample {
public static void main(String[] args) {
//Create Ignite instance
IgniteConfiguration cfg = new IgniteConfiguration();
cfg.setIgniteInstanceName("myIgniteInstance");
cfg.setPeerClassLoadingEnabled(true);
Ignite ignite = Ignition.start(cfg);
//Create cache configuration
CacheConfiguration<Integer, String> cacheCfg = new CacheConfiguration<>("myCache");
cacheCfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);
//Obtain or create an Ignite cache
IgniteCache<Integer, String> cache = ignite.getOrCreateCache(cacheCfg);
//Insert Data
cache.put(1, "John");
cache.put(2, "Jane");
//Modify data
cache.replace(1, "John", "Jonathan");
//Query data
String name = cache.get(1);
System.out.println(name);
//Delete data
cache.remove(1);
//Close Ignite instance
ignite.close();
}
}
This is a simple example of using Java to operate Apache Ignite. You can further flexibly operate and configure according to your needs.