Introduction to LRU Cache
LRU (Least Recently Used) cache is a type of cache algorithm that removes the least recently accessed items first. It is useful in scenarios where you want to ensure that the cache contains the most frequently accessed items, which can significantly improve the performance of your application by reducing the time required to fetch data from a slower storage medium.
Key Features and API Usage
Let’s dive into some of the essential APIs provided by LRU cache implementation with code snippets in Python.
1. Initializing the LRU Cache
from cachetools import LRUCache
# Initialize the cache with a maximum size of 3
cache = LRUCache(maxsize=3)
2. Adding Items to the Cache
# Adding items to the cache
cache['item1'] = 'A'
cache['item2'] = 'B'
cache['item3'] = 'C'
3. Accessing Items from the Cache
# Accessing an item
value = cache['item1']
print(value) # Output: A
4. Handling Cache Misses
try:
value = cache['item4']
except KeyError:
print("Item not found in cache")
5. Updating Existing Items
# Updating an existing item
cache['item1'] = 'AA'
6. Deleting Items from the Cache
# Deleting an item from the cache
del cache['item2']
7. Checking Cache Size
# Checking the number of items in the cache
size = len(cache)
print(size) # Output: 2
8. Clearing the Cache
# Clearing all items from the cache
cache.clear()
9. Example Application Using LRU Cache
Here is a simple example of how LRU cache can be implemented in a web application to cache database query results.
from flask import Flask, jsonify
from cachetools import LRUCache
app = Flask(__name__)
cache = LRUCache(maxsize=5)
def get_data_from_db(key):
# Simulate a database call
return {'data': f'Data for {key}'}
@app.route('/data/')
def get_data(key):
if key in cache:
return jsonify({'cached': True, 'data': cache[key]})
data = get_data_from_db(key)
cache[key] = data
return jsonify({'cached': False, 'data': data})
if __name__ == '__main__':
app.run(debug=True)
In this example, we use a simple Flask application to serve data that is cached using LRU cache. When a request is made, it first checks if the data is available in the cache before fetching it from the database. This reduces the number of database hits and speeds up response times.
Hash: 9872a5bb267f9a3a0a194693fd1b43bc428d9f77b12a9734045fa0964b806ea5