Tuesday 23 August 2016

Memcached: gets : Get data with CAS token

‘gets’ command is used to get the value with CAS token. CAS stands for check and set. CAS token is very useful in concurrent applications. For example, you want to deduct some amount from customer account on every transaction.

Thread 1 reads cust1 account balance as 1500
Thread 2 also reads the cust1 account balance as 1500
Thread 2 deduct 300 from cust1 account = 1500-300 = 1200
Thread 1 deduct 100 from cust1 account = 1500-100 = 1400.

As you see above flow, Actual balance to be deducted from cust1 account is 400, but final amount is 1400. To handle these kind of scenarios, we should use CAS command. I will explain about CAS command in next post, let us concentrate on gets command here.

Syntax
gets key

You can also get the values associated with multiple keys at a time.

Syntax
gets key1 key2….keyN
$ telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
set 1 0 900 11
harikrishna
STORED
gets 1
VALUE 1 0 11 30
harikrishna
END

As you see 30 at the end, 30 is the unique CAS token value associated with the key 1.


Let me try to update the data associated with key 1 and recheck the value of CAS token.
set 1 0 900 5 
India
STORED
gets 1
VALUE 1 0 5 31
India
END


As you see, CAS token value is incremented by 1 (31). Assume CAS token as version of the data, while updating you can specify that, you want to update value of specific version, If memcached server has the same version, then your update operation will be successful, else you will get an error. You can achieve this kind of behavior using  ‘CAS’ command. I am going to explain this in next post.


Previous                                                 Next                                                 Home

No comments:

Post a Comment