ID generator

An ID generator should sequentially generate unique IDs across the cluster. In all our examples, we created hardcoded IDs for cache keys or used a database to generate a unique ID. Sequential ID generation is an important task in distributed computing. Ignite provides the IgniteCacheAtomicSequence interface to generate an atomic sequence.

The following code snippet creates an IgniteCacheAtomicSequence interface:

      IgniteAtomicSequence seq = ignite.atomicSequence(
"name", // name of sequence generate
0, // Initial value for sequence.
true // Create if it does not exist.
);

In the real world, the initial value can be read from a persistent store and set in IgniteCacheAtomicSequence.

In this section, we'll create a sequence generator and send it across the cluster to generate IDs. The following are the requisite steps:

  1. Create a program called IdGeneratorTest and start an Ignite instance:
      public class IdGeneratorTest {
public static void main(String[] args) {
IgniteConfiguration cfg = new IgniteConfiguration();
cfg.setClientMode(true);
cfg.setPeerClassLoadingEnabled(true);
Ignite ignite = Ignition.start(cfg);
  1. Create an instance of the IgniteAtomicSequence generator with the initial value 0
      IgniteAtomicSequence seq = ignite.atomicSequence("mySeq", 
0, true);
  1. Create a semaphore with permit set to 7. The main thread will wait for worker threads to finish using this semaphore:
       IgniteSemaphore semaphore = ignite.semaphore("mySync", 7, 
true, true);
  1. Create an ExecutorService instance for worker thread distribution: 
      ExecutorService executorService = ignite.executorService();
  1. Submit seven worker jobs. In the run method, increment the seq number and release a semaphore permit for the main thread:
      IntStream.range(1, 8).forEach(i -> executorService.execute
(new Runnable() {
@Override
public void run() {
System.out.println(String.format("Thread Index %s -
Sequence id is %s", i, seq.incrementAndGet()));
semaphore.release();
try {
Thread.sleep(300);
} catch (InterruptedException e) {e.printStackTrace();}
}
}));
  1. In the main thread, wait for the seven permits. Once all seven permits are released, print that the worker threads are done:
       semaphore.acquire(7);
System.out.println("Processing done");
  1. Launch two Ignite servers and run this program. It will print unique sequence IDs in remote nodes. The following is an example output:

We can configure our atomic sequencer using AtomicConfiguration.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.137.58