ignitedistributed-caching

Atomic operations across two ignite caches


I have two ignite caches. Both of them use the key/value pairs (and there is no database involved) to store some data.

The cache1 stores the actual data, whereas the cache2 stores some metadata. The requirement is to make sure that both the caches are always in sync even in case of any problem.

Is there a way I can make sure that both the updates are guaranteed to occur? If one of the operations fails, then the other one should also be rolled back.

Here is the sample code

cache1.put(someKey, someValue);
// some other code
cache2.put(anotherKey, anotherValue);

How do I make sure either both the caches are updated or none?


Solution

  • Yes, you need to use transactions. For example:

    Ignite ignite = Ignition.ignite();
    
    IgniteTransactions transactions = ignite.transactions();
    
    try (Transaction tx = transactions.txStart()) {
      Integer hello = cache.get("Hello");
    
      if (hello == 1)
        cache.put("Hello", 11);
    
      cache.put("World", 22);
    
      tx.commit(); 
    }
    

    Both your caches need to have atomicityMode parameter set to TRANSACTIONAL for this to work (the default is ATOMIC).