Memcached
Memcached was written to reduce the number of database queries, which is built as a general purpose ultrafast memory-based caching service.
(Work in a highly scalable manner, that you can run memcached in a consistent-hashing-based cluster and your cache will be partitioned across as many machines as you like.)
Use memcache in Python
- Install related packages
pip3 install python-memcached
- Use memcached in python
import memcache
memc = memcache.Client(['127.0.0.1:11211'])
import sys
import MySQLdb
import memcache
memc = memcache.Client(['127.0.0.1:11211'], debug=1);
try:
conn = MySQLdb.connect (host = "localhost",
user = "sakila",
passwd = "password",
db = "sakila")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
popularfilms = memc.get('top5films')
if not popularfilms:
cursor = conn.cursor()
cursor.execute('select film_id,title from film order by rental_rate desc limit 5')
rows = cursor.fetchall()
memc.set('top5films',rows,60)
print "Updated memcached with MySQL data"
else:
print "Loaded data from memcached"
for row in popularfilms:
print "%s, %s" % (row[0], row[1])
Python memcache Function Equivalent Generic Function
get() Generic get().
get_multi(keys)
Gets multiple values from the supplied array of keys. Returns a hash reference of key/value pairs.
set() Generic set().
set_multi(dict [, expiry [, key_prefix]])
Sets multiple key/value pairs from the supplied dict.
add() Generic add().
replace() Generic replace().
prepend(key, value [, expiry]) Prepends the supplied value to the value of the existing key.
append(key, value [, expiry[) Appends the supplied value to the value of the existing key.
delete() Generic delete().
delete_multi(keys [, expiry [, key_prefix]] )
Deletes all the keys from the hash matching each string in the array keys.
incr() Generic incr().
decr() Generic decr().
[MySQL Memcached](https://dev.mysql.com/doc/mysql-ha-scalability/en/ha-memcached-interfaces-python.html\)