In our microservice, we exposed 2 APIs both of them finally try to read, insert and update the same resource. So to avoid data inconsistency we try to serialize the request by taking lock-on the key (the key is derived from request data and always be the same in both APIs).
code Snippet
Session session = sessionFactory.openSession();
String lockKey = "key-name";
try {
// acquire lock query= SELECT GET_LOCK(lockKey, 5000)
hibernateMysqlLock.acquireLockOrException(lockKey, session);
someService.execute(someObject);
} finally {
// releasing lock query= SELECT RELEASE_LOCK(lockKey)
hibernateMysqlLock.release(lockKey, session);
session.close();
}
Most of the time SELECT RELEASE_LOCK(lockKey) is not releasing lock and return 0 and 0 means the lock was not established by this thread (in which case the lock is not released), (according to doc https://dev.mysql.com/doc/refman/5.7/en/locking-functions.html#function_release-lock)
Need help in fixing issue and also suggest better approach if possible
Tech Stack: dropwizard (with hibernate) and MySQL (as datastore)