Introduction to Memcached
Memcached is a high-performance, distributed memory caching system that is used to speed up dynamic web applications by alleviating database load. This tutorial will provide a comprehensive guide to dozens of useful APIs offered by Memcached along with code snippets.
Basic Operations
Set Data
import memcache
# Connect to memcached
client = memcache.Client([('127.0.0.1',11211)])
# Set a value
client.set('key', 'value')
Get Data
value = client.get('key')
print(value) # Output: value
Delete Data
client.delete('key')
Advanced Operations
Increment a Value
client.set('counter', 1)
client.incr('counter', 1)
value = client.get('counter')
print(value) # Output: 2
Decrement a Value
client.set('counter', 2)
client.decr('counter', 1)
value = client.get('counter')
print(value) # Output: 1
Append Data
client.set('key', 'Hello')
client.append('key', ' World')
value = client.get('key')
print(value) # Output: Hello World
Prepend Data
client.set('key', 'World')
client.prepend('key', 'Hello ')
value = client.get('key')
print(value) # Output: Hello World
Simple Application Example
Web Page Cache
from flask import Flask, request
import memcache
app = Flask(__name__)
client = memcache.Client([('127.0.0.1', 11211)])
@app.route('/')
def homepage():
# Try fetching cached data
page_cache = client.get('homepage')
if page_cache:
return page_cache
# Processing the page
page_content = "Home Page Content"
# Cache the page content
client.set('homepage', page_content, time=60)
return page_content
if __name__ == "__main__":
app.run()
By using the cache API provided by memcached, the application can handle more requests, enhancing overall performance and user experience.
Hash: 9f12aa1e1352e96b0e03dce9945f55a918e667d1dd4f088930d62db22b4ab166