From 23ef0b978775b568391c9b79cd21d6ad3a70b7b1 Mon Sep 17 00:00:00 2001 From: Pavel Kartavyy Date: Wed, 4 Mar 2015 19:15:32 +0300 Subject: [PATCH] zkutil: add Increment [#METR-15299] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ███████████: write clicks to cloud [#METR-15299] --- libs/libzkutil/include/zkutil/Increment.h | 47 +++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 libs/libzkutil/include/zkutil/Increment.h diff --git a/libs/libzkutil/include/zkutil/Increment.h b/libs/libzkutil/include/zkutil/Increment.h new file mode 100644 index 00000000000..bc8925fe4fc --- /dev/null +++ b/libs/libzkutil/include/zkutil/Increment.h @@ -0,0 +1,47 @@ +#pragma once + +#include + +namespace zkutil +{ + +class Increment +{ +public: + Increment(ZooKeeperPtr zk_, const std::string & path_) + : zk(zk_), path(path_) + { + } + + size_t get() + { + LOG_TRACE(log, "Get increment"); + + size_t result = 0; + std::string result_str; + zkutil::Stat stat; + + bool success = false; + do + { + if (zk->tryGet(path, result_str, &stat)) + { + result = std::stol(result_str) + 1; + success = zk->trySet(path, std::to_string(result), stat.version) == ZOK; + } + else + { + success = zk->tryCreate(path, std::to_string(result), zkutil::CreateMode::Persistent) == ZOK; + } + } + while(!success); + + return result; + } +private: + zkutil::ZooKeeperPtr zk; + std::string path; + Logger * log = &Logger::get("zkutil::Increment"); +}; + +} \ No newline at end of file