2015-03-04 16:15:32 +00:00
|
|
|
#pragma once
|
|
|
|
|
2015-12-14 11:49:50 +00:00
|
|
|
#include <zkutil/ZooKeeperHolder.h>
|
2015-03-04 16:15:32 +00:00
|
|
|
|
2015-04-22 17:56:27 +00:00
|
|
|
namespace zkutil
|
2015-03-04 16:15:32 +00:00
|
|
|
{
|
2017-03-31 16:00:30 +00:00
|
|
|
|
2015-03-04 16:15:32 +00:00
|
|
|
class Increment
|
|
|
|
{
|
|
|
|
public:
|
2017-04-01 07:20:54 +00:00
|
|
|
Increment(ZooKeeperHolderPtr zk_holder_, const std::string & path_)
|
|
|
|
: zookeeper_holder(zk_holder_), path(path_)
|
|
|
|
{
|
|
|
|
zookeeper_holder->getZooKeeper()->createAncestors(path);
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t get()
|
|
|
|
{
|
|
|
|
LOG_TRACE(log, "Get increment");
|
|
|
|
|
|
|
|
size_t result = 0;
|
|
|
|
std::string result_str;
|
|
|
|
zkutil::Stat stat;
|
|
|
|
|
|
|
|
bool success = false;
|
|
|
|
auto zookeeper = zookeeper_holder->getZooKeeper();
|
|
|
|
do
|
|
|
|
{
|
|
|
|
if (zookeeper->tryGet(path, result_str, &stat))
|
|
|
|
{
|
|
|
|
result = std::stol(result_str) + 1;
|
|
|
|
success = zookeeper->trySet(path, std::to_string(result), stat.version) == ZOK;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
success = zookeeper->tryCreate(path, std::to_string(result), zkutil::CreateMode::Persistent) == ZOK;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
while (!success);
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
2015-03-04 16:15:32 +00:00
|
|
|
private:
|
2017-04-01 07:20:54 +00:00
|
|
|
zkutil::ZooKeeperHolderPtr zookeeper_holder;
|
|
|
|
std::string path;
|
|
|
|
Logger * log = &Logger::get("zkutil::Increment");
|
2015-03-04 16:15:32 +00:00
|
|
|
};
|
|
|
|
|
2015-04-22 17:56:27 +00:00
|
|
|
}
|