Created
June 15, 2012 06:03
-
-
Save bradclawsie/2934941 to your computer and use it in GitHub Desktop.
loadredis.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <string> | |
#include <vector> | |
#include <ctime> | |
#include <random> | |
#include <hiredis/hiredis.h> | |
int main() { | |
const std::time_t now = std::time(NULL); | |
const std::time_t yest = now - 86400; | |
std::string line; | |
std::ifstream fh ("/etc/dictionaries-common/words"); | |
std::vector<std::string> words; | |
// read the dict into a vector | |
ulong c = 0; | |
if (fh.is_open()) { | |
while (fh.good()) { | |
getline(fh,line); | |
if (line.length() > 0) { | |
words.push_back(line); | |
c++; | |
} | |
} | |
fh.close(); | |
} | |
c--; // we will treat this as zero offset | |
// the pseudo-random number generator | |
std::mt19937 prng; | |
// seed it with the current utc time, a suitable uint32_t | |
prng.seed(now); | |
// over the range of 0..count of words in the dict file, c | |
std::uniform_int_distribution<uint32_t> pr_word_index(0,c); | |
// connect to redis | |
redisContext *conn; | |
redisReply *reply; | |
const struct timeval timeout = { 1, 500000 }; // 1.5 seconds | |
conn = redisConnectWithTimeout((char*)"127.0.0.1", 6379, timeout); | |
if (conn->err) { | |
std::cerr << "connection error " << conn->errstr << std::endl; | |
exit(1); | |
} | |
reply = (redisReply *) redisCommand(conn,"FLUSHALL"); | |
freeReplyObject(reply); | |
// for each second, get a random word, then insert it into redis | |
for (auto i=yest;i<=now;i++) { | |
// random word index | |
const uint32_t r = pr_word_index(prng); | |
const std::string rw = words.at(r); | |
const std::string is = std::to_string(i); | |
reply = (redisReply *) redisCommand(conn,"SET %s %s",is.c_str(),rw.c_str()); | |
if (reply->type != REDIS_REPLY_STATUS) { | |
std::cerr << "set err " << reply->str << std::endl; | |
exit(1); | |
} | |
freeReplyObject(reply); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment