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