Cache Python MySQL Result using Redis
We’re often using MySQL so much, like read data from DB, calculate something, write data with index. And I bet You know, that process is also using your i/o machine. I prefer my CPU usage 100% than my i/o 50%.
Redis is live in memory, so it won’t do anything like read / write to disk that make your i/o process high (untill your max memory, if it’s not enough, redis create virtual memory, CMIIW). I plan to make my application faster and faster with caching using redis, and I will improve my news web crawler to going faster with redis as cache.
The code
Explanation
Check Redis Key, if exists, just return it
If not exists, do MySQL query, and set the key, then return it
Why I use serialization with cPickle? because Redis just store the string with SET Command, so, our MySQL result must serialize to string, and cPickle is faster than pickle or marshal (cmiiw).
Conclusion
This simple post is just to show how to use cache python mysql result using redis. And in my opinion, redis just awesome
Better code view