Skip to content

Commit

Permalink
Merge pull request #4 from camargo2019/fix/expire-cache
Browse files Browse the repository at this point in the history
🩹 fix: expire cache
  • Loading branch information
camargo2019 authored Sep 9, 2024
2 parents b1ef74e + 0dc6ffe commit efdc26e
Show file tree
Hide file tree
Showing 5 changed files with 22 additions and 2 deletions.
2 changes: 1 addition & 1 deletion TODO.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
## 📌 Tarefas Pendentes

### Funcionalidades
- [ ] Implementar expiração dos valores ao utilizar o comando `SET key value expire`.
- [x] Implementar expiração dos valores ao utilizar o comando `SET key value expire`.

### Melhorias
- [ ] Melhorar o método de salvamento dos dados no arquivo `.dat`.
Expand Down
17 changes: 17 additions & 0 deletions core/cache/cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,21 @@ void Cache::save(){
cachedata.serialize(file);
}
}
}

void Cache::expire(){
std::thread([this]() {
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
for (auto& row: cache_) {
for (auto& item: row.second) {
if (item.second.expire == 0){
del(row.first, item.first);
}else if(item.second.expire > 0){
--item.second.expire;
}
}
}
}
}).detach();
}
3 changes: 3 additions & 0 deletions core/cache/cache.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@

#include <string>
#include <vector>
#include <thread>
#include <chrono>
#include <fstream>
#include <unordered_map>

Expand Down Expand Up @@ -55,6 +57,7 @@
bool del(std::string db, std::string key);
std::vector<std::string> keys (std::string db);
void save();
void expire();

private:
std::unordered_map<std::string, std::unordered_map<std::string, CacheStruct>> cache_;
Expand Down
1 change: 0 additions & 1 deletion core/manager/manager.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
#ifndef CORE_MANAGER_H
#define CORE_MANAGER_H

#include <string>
#include <string>
#include <vector>
#include <memory>
Expand Down
1 change: 1 addition & 0 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

int main(){
Cache cache_;
cache_.expire();

try {
boost::asio::io_context io_context;
Expand Down

0 comments on commit efdc26e

Please sign in to comment.