【GitHub】:示例代码
uuid 通用唯一识别码:配置 curl URL传输:配置 JSON for Modern C++:配置
#pragma once
#include <cstdio>
#include <iostream>
#include <list>
#include <string>
#include <tr1/unordered_map>
#include <set>
#include <thread>
#include <locale>
#include <codecvt>
#include <algorithm>
#include <unistd.h>
#include <curl/curl.h>
#include <sw/redis++/redis++.h>
#include <uuid/uuid.h>
#include <nlohmann/json.hpp>
using namespace sw::redis;
class chapter_02
{
public:
void run()
{
auto redis = Redis("tcp://123456@192.168.xxx.xxx:6379");
try
{
}
catch (std::exception& err)
{
std::cout << err.what() << std::endl;
}
}
class rescale_viewed
{
private:
Redis redis_;
bool quit_;
public:
rescale_viewed(std::string cnf) :
redis_(Redis(cnf)),
quit_(false)
{}
void quit()
{
quit_ = true;
}
void run()
{
while (!quit_)
{
redis_.zremrangebyrank("viewed:", 20000, -1);
redis_.zinterstore("viewed:", "viewed:", 0.5);
sleep(300);
}
}
};
};
void test_login_cookies(Redis& redis)
{
std::cout << "\n----- testLoginCookies -----" << std::endl;
uuid_t uuid;
char buf[36];
uuid_generate_random(uuid);
uuid_unparse(uuid, buf);
std::string token = buf;
update_token(redis, token, "username", "itemX");
std::cout << "We just logged-in/updated token: " + token << std::endl;
std::cout << "For user: 'username'" << std::endl;
std::cout << std::endl;
std::cout << "What username do we get when we look-up that token?" << std::endl;
auto r = check_token(redis, token);
std::cout << r << std::endl;
std::cout << std::endl;
assert(r.length() != 0);
std::cout << "Let's drop the maximum number of cookies to 0 to clean them out" << std::endl;
std::cout << "We will start a thread to do the cleaning, while we stop it later" << std::endl;
auto obj = clean_sessions("tcp://123456@192.168.xxx.xxx:6379", 0);
auto thread = std::thread(&clean_sessions::run, &obj);
sleep(1);
obj.quit();
thread.join();
if (thread.joinable())
{
throw std::runtime_error("The clean sessions thread is still alive?!?");
}
auto s = redis.hlen("login:");
std::cout << "The current number of sessions still available is: " + std::to_string(s) << std::endl;
assert(s == 0);
}
std::string check_token(Redis& redis, std::string token)
{
auto res = redis.hget("login:", token);
if (res) return res.value();
return "";
}
void update_token(Redis& redis, std::string token, std::string user, std::string item)
{
auto timestamp = time(NULL);
redis.hset("login:", token, user);
redis.zadd("recent:", token, static_cast<double>(timestamp));
if (item.length())
{
redis.zadd("viewed:" + token, item, static_cast<double>(timestamp));
redis.zremrangebyrank("viewed:" + token, 0, -26);
redis.zincrby("viewed:", -1, item);
}
}
class clean_sessions
{
private:
Redis redis_;
long long limit_;
bool quit_;
public:
clean_sessions(std::string cnf, int limit = 10000000) :
redis_(Redis(cnf)),
limit_(limit),
quit_(false)
{}
void quit()
{
quit_ = true;
}
void run()
{
while (!quit_)
{
auto size = redis_.zcard("recent:");
if (size <= limit_)
{
try
{
sleep(1);
}
catch (std::exception& err)
{
std::cout << err.what() << std::endl;
return;
}
continue;
}
auto end_index = std::min(size - limit_, (long long)100);
std::vector<std::string> tokens;
redis_.zrange("recent:", 0, end_index - 1, std::back_inserter(tokens));
std::vector<std::string> session_keys;
for (auto token : tokens)
session_keys.push_back("viewed:" + token);
redis_.del(session_keys.begin(), session_keys.end());
redis_.hdel("login:", tokens.begin(), tokens.end());
redis_.zrem("recent:", tokens.begin(), tokens.end());
}
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/663fa084b06fc519597238be4cc28aba.jpeg)
void test_shoppping_cart_cookies(Redis& redis)
{
std::cout << "\n----- testShopppingCartCookies -----" << std::endl;
uuid_t uuid;
char buf[37] = { 0 };
uuid_generate_random(uuid);
uuid_unparse(uuid, buf);
std::string token = buf;
std::cout << "We'll refresh our session..." << std::endl;
update_token(redis, token, "username", "itemX");
std::cout << "And add an item to the shopping cart" << std::endl;
add_to_cart(redis, token, "itemY", 3);
std::unordered_map<std::string, std::string> r;
redis.hgetall("cart:" + token, std::inserter(r, r.begin()));
std::cout << "Our shopping cart currently has:" << std::endl;
for (auto& item : r)
{
std::cout << " " + item.first + ": " + item.second << std::endl;
}
std::cout << std::endl;
assert(r.size() >= 1);
std::cout << "Let's clean out our sessions and carts" << std::endl;
auto obj = clean_full_sessions("tcp://123456@192.168.xxx.xxx:6379", 0);
auto thread = std::thread(&clean_full_sessions::run, &obj);
sleep(1);
obj.quit();
thread.join();
if (thread.joinable())
{
throw std::runtime_error("The clean sessions thread is still alive?!?");
}
std::unordered_map<std::string, std::string> r2;
redis.hgetall("cart:" + token, std::inserter(r2, r2.begin()));
std::cout << "Our shopping cart now contains:" << std::endl;
for (auto& item : r2)
{
std::cout << " " + item.first + ": " + item.second << std::endl;
}
assert(r2.size() == 0);
}
void add_to_cart(Redis& redis, std::string session, std::string item, int count)
{
if (count <= 0)
redis.hdel("cart:" + session, item);
else
redis.hset("cart:" + session, item, std::to_string(count));
}
class clean_full_sessions
{
private:
Redis redis_;
long long limit_;
bool quit_;
public:
clean_full_sessions(std::string cnf, int limit = 10000000) :
redis_(Redis(cnf)),
limit_(limit),
quit_(false)
{}
void quit()
{
quit_ = true;
}
void run()
{
while (!quit_)
{
long size = redis_.zcard("recent:");
if (size <= limit_)
{
try
{
sleep(1);
}
catch (std::exception& err)
{
std::cout << err.what() << std::endl;
return;
}
continue;
}
auto end_index = std::min(size - limit_, (long long)100);
std::vector<std::string> sessions;
redis_.zrange("recent:", 0, end_index - 1, std::back_inserter(sessions));
std::vector<std::string> session_keys;
for (auto sess : sessions)
{
session_keys.push_back("viewed:" + sess);
session_keys.push_back("cart:" + sess);
}
redis_.del(session_keys.begin(), session_keys.end());
redis_.hdel("login:", sessions.begin(), sessions.end());
redis_.zrem("recent:", sessions.begin(), sessions.end());
}
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b869a46b47218440144a5655664c436b.jpeg)
void test_cache_rows(Redis& redis)
{
std::cout << "\n----- testCacheRows -----" << std::endl;
std::cout << "First, let's schedule caching of itemX every 5 seconds" << std::endl;
schedule_row_cache(redis, "itemX", 5);
std::cout << "Our schedule looks like:" << std::endl;
std::unordered_map<std::string, double> res_with_score;
redis.zrange("schedule:", 0, -1, std::inserter(res_with_score, res_with_score.end()));
for (auto& item : res_with_score)
{
std::cout << " " + item.first + ", " + std::to_string(item.second) << std::endl;
}
assert(res_with_score.size() != 0);
std::cout << "We'll start a caching thread that will cache the data..." << std::endl;
auto obj = cache_rows("tcp://123456@192.168.xxx.xxx:6379");
auto thread = std::thread(&cache_rows::run, &obj);
sleep(1);
std::cout << "Our cached data looks like:" << std::endl;
auto r = redis.get("inv:itemX");
std::string rf = r ? r.value() : "";
std::cout << rf << std::endl;
assert(rf.length() != 0);
std::cout << std::endl;
std::cout << "We'll check again in 5 seconds..." << std::endl;
sleep(5);
std::cout << "Notice that the data has changed..." << std::endl;
auto r2 = redis.get("inv:itemX");
std::string r2f = r2 ? r2.value() : "";
std::cout << r2f << std::endl;
std::cout << std::endl;
assert(r2f.length() != 0);
assert(rf.compare(r2f) != 0);
std::cout << "Let's force un-caching" << std::endl;
schedule_row_cache(redis, "itemX", -1);
sleep(1);
auto r3 = redis.get("inv:itemX");
std::string r3f = r3 ? "false" : "true";
std::cout << "The cache was cleared? " + r3f << std::endl;
assert(!r3f.compare("true"));
obj.quit();
thread.join();
if (thread.joinable())
{
throw std::runtime_error("The database caching thread is still alive?!?");
}
}
class cache_rows
{
private:
Redis redis_;
bool quit_;
static inventory inventory_;
public:
cache_rows(std::string cnf) :
redis_(Redis(cnf)),
quit_(false)
{}
void quit()
{
quit_ = true;
}
void run()
{
nlohmann::json j;
while (!quit_)
{
std::unordered_map<std::string, double> res_with_score;
redis_.zrange("schedule:", 0, 0, std::inserter(res_with_score, res_with_score.end()));
auto next = res_with_score.begin();
auto now = time(NULL);
if (next == res_with_score.end() || (*next).second > static_cast<double>(now))
{
try
{
usleep(50000);
}
catch (std::exception& err)
{
std::cout << err.what() << std::endl;
return;
}
continue;
}
auto row_id = (*next).first;
double delay = redis_.zscore("delay:", row_id).value();
if (delay <= 0)
{
redis_.zrem("delay:", row_id);
redis_.zrem("schedule:", row_id);
redis_.del("inv:" + row_id);
continue;
}
auto row = inventory_.get(row_id);
redis_.zadd("schedule:", row_id, static_cast<double>(now) + delay);
row.to_json(j);
redis_.set("inv:" + row_id, j.dump());
}
}
};
class inventory
{
public:
std::string id_;
std::string data_;
long time_;
private:
inventory(std::string id)
{
id_ = id;
data_ = "data to cache...";
time_ = time(NULL);
}
public:
static inventory get(std::string id)
{
return inventory(id);
}
void to_json(nlohmann::json& j)
{
j = nlohmann::json{ {"id", id_}, {"data", data_}, {"time", time_} };
}
void from_json(const nlohmann::json& j)
{
j.at("id").get_to(id_);
j.at("data").get_to(data_);
j.at("time").get_to(time_);
}
};
void schedule_row_cache(Redis& redis, std::string row_id, int delay)
{
redis.zadd("delay:", row_id, delay);
redis.zadd("schedule:", row_id, static_cast<double>(time(NULL)));
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/aec7b5453b97019b7e73fcd0bdde85c1.jpeg)
void test_cache_request(Redis& redis)
{
std::cout << "\n----- testCacheRequest -----" << std::endl;
uuid_t uuid;
char buf[36];
uuid_generate_random(uuid);
uuid_unparse(uuid, buf);
auto token = std::string(buf);
auto cb = new request_call_back;
update_token(redis, token, "username", "itemX");
auto url = std::string("http://test.com/?item=itemX");
std::cout << "We are going to cache a simple request against " + url << std::endl;
auto result = cache_request(redis, url, cb);
std::cout << "We got initial content:\n" + result << std::endl;
std::cout << std::endl;
assert(result.length() != 0);
std::cout << "To test that we've cached the request, we'll pass a bad callback" << std::endl;
auto result2 = cache_request(redis, url, NULL);
std::cout << "We ended up getting the same response!\n" + result2 << std::endl;
assert(!result.compare(result2));
assert(!can_cache(redis, "http://test.com/"));
assert(!can_cache(redis, "http://test.com/?item=itemX&_=1234536"));
}
class call_back
{
public:
virtual std::string call(std::string request)
{
return "";
}
};
class request_call_back : public call_back
{
public:
std::string call(std::string request) override
{
return "content for " + request;
}
};
std::string cache_request(Redis& redis, std::string request, call_back* db)
{
if (!can_cache(redis, request))
{
return db != NULL ? db->call(request) : "";
}
auto page_key = "cache:" + hash_request(request);
auto content = redis.get(page_key);
std::string res = "";
if ((!content) && db != NULL)
{
res = db->call(request);
redis.setex(page_key, 300, res);
}
else
{
res = content.value();
}
return res;
}
bool can_cache(Redis& redis, std::string request)
{
try
{
auto report = req(request);
std::unordered_map<std::string, std::string> params;
if (report.length() != 0)
{
auto pms = util::split(report, "&");
for (auto param : pms)
{
auto pos = param.find("=");
if (pos != std::string::npos)
{
auto first = param.substr(0, pos);
auto second = param.substr(pos + 1, param.length());
params[first] = second;
}
else
params[param] = "";
}
}
auto item_id = extract_item_id(params);
if (item_id.length() == 0 || is_dynamic(params))
return false;
auto rank = redis.zrank("viewed:", item_id);
return rank && (rank.value() < static_cast<long long>(10000));
}
catch (std::exception& err)
{
return false;
}
}
bool is_dynamic(std::unordered_map<std::string, std::string>& params)
{
return params.find("_") != params.end();
}
std::string extract_item_id(std::unordered_map<std::string, std::string>& params)
{
if(params.find("item") != params.end())
return params["item"];
return "";
}
std::string hash_request(std::string request)
{
return std::to_string(util::hash_code(request));
}
std::string req(std::string request)
{
CURL* curl;
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, request.c_str());
curl_easy_setopt(curl, CURLOPT_SSLVERSION, 1);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
curl_easy_setopt(curl, CURLOPT_POST, 0);
std::string report_header = "";
std::string report = "";
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, _CURL_::write_data);
curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &report_header);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _CURL_::write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &report);
CURLcode code = curl_easy_perform(curl);
if (code != CURLE_OK)
{
printf("curl_wasy_perform error = %s", curl_easy_strerror(code));
}
curl_easy_cleanup(curl);
return report;
}
因无法向http://test.com/?item=itemX等地址发送请求,故注释can_cache以运行
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/95127ea72c06ac9f71e33531f1f3f1d6.jpeg)
namespace util
{
std::wstring s2ws(const std::string& str)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.from_bytes(str);
}
std::string ws2s(const std::wstring& wstr)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
int32_t hash_code(const std::string& str)
{
int32_t h = 0;
auto wstr = s2ws(str);
if (h == 0 && wstr.length() > 0)
{
for (uint32_t i = 0; i < wstr.length(); i++)
{
h = 31 * h + wstr.at(i);
}
}
return h;
}
std::vector<std::string> split(const std::string& src, const std::string& pattern)
{
std::vector<std::string> res;
if (src == "")
return res;
std::string strcom = src + pattern;
auto pos = src.find(pattern);
auto len = strcom.size();
while (pos != std::string::npos)
{
auto costr = strcom.substr(0, pos);
res.push_back(costr);
strcom = strcom.substr(pos + pattern.size(), len);
pos = strcom.find(pattern);
}
return res;
}
}
namespace _CURL_
{
static size_t write_data(void* buf, size_t unit, size_t bufSize, std::string* data)
{
size_t size = unit * bufSize;
char* tmp = (char*)malloc(size + 1);
memcpy(tmp, buf, size);
tmp[size] = '\0';
data->append(tmp);
free(tmp);
return size;
}
class curl_intelligence
{
public:
curl_intelligence()
{
curl_global_init(CURL_GLOBAL_ALL);
}
~curl_intelligence()
{
curl_global_cleanup();
}
};
}
_CURL_::curl_intelligence g_curl;