结合使用redis和Flask_caching。数据更改时,应用会使用cache.clear()
清除Redis键,这是可行的。但是,当用户请求页面不在数据库中的记录页面时,redis会填充键。我想将TTL至少保留一周或更长时间。因此,应用程序需要删除无效密钥,因为它们会随着时间的推移而填满Redis。我查看了cache.delete()
,redis.expire()
和cache.set()
,但是在请求期间它们都不起作用。似乎redis条目仅在请求之后创建,因此我无法更改TTL或将其删除。
我决定采用这种解决方案。
@home.route('/product/<int:product_id>')
@cache.cached()
def view_product(product_id):
data = Product.query.filter_by(id=product_id).filter_by(active=True).first()
if data is None:
message = 'Invalid Product'
prefix = current_app.config['CACHE_KEY_PREFIX']
deleteBadCacheList = f"{prefix}INVALID"
key = f"{prefix}view/{request.path}"
redis.lpush(deleteBadCacheList, key)
for key in redis.lrange(deleteBadCacheList, 0, -1):
key = key.decode("utf-8")
if redis.exists(key):
redis.expire(key, 1)
redis.lrem(deleteBadCacheList, 0, key)
....
return render_template('product.html', flash=message, product=data.serialized)
通过这种方法,将无效产品的请求存储在Redis范围键<prefix>INVALID
中。每次再次发出请求时,对于无效产品,应用程序都会从先前失败的请求中删除项目。我觉得有更好的方法。在我看来,大多数应用程序都会出现此问题。有什么建议吗?