0

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?

Yasin
  • 1,906
  • 1
  • 21
  • 37

1 Answers1

3

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).

Stephen Darlington
  • 51,577
  • 12
  • 107
  • 152
  • Thanks, @Stephen Darlington, can I use two different caches in the same transaction block? I have updated the question to provide a code sample. Moreover, I see that the transaction is obtained on `ignite` rather than a specific cache. Will this impact other threads/caches while the transaction is being executed? – Yasin Aug 25 '20 at 09:54
  • @Yasin As long as they're both TRANSACTIONAL it'll work. It'll impact other caches/threads in the sense that records will be locked. You can change it to use optimistic locking if it's unlikely that two processes will change the same record. – Stephen Darlington Aug 25 '20 at 13:15
  • 2
    @Yasin check out these two recordings that cover Ignite transactions in detail: 1) Architects' Guide for Apache Ignite ACID Transactions and Consistency: https://youtu.be/TCsl-W0tsEE 2) Moving Apache Ignite into Production: Best Practices for Distributed Transactions: https://youtu.be/yvMWK-4grYo – dmagda Aug 25 '20 at 15:30