You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Functions Python全局内存缓存失效问题排查咨询

问题分析与修复方案

核心问题

你的内存缓存未生效主要是类方法定义错误导致的,次要问题是代码中存在参数缺失的错误。

1. 类方法参数传递异常

InMemoryCache中的get_cache和set_cache方法没有使用@staticmethod或@classmethod装饰器。在Python中,直接通过类调用未装饰的类方法时,解释器会自动将类对象作为第一个参数传入方法,导致你传入的key参数被挤到第二位,实际缓存查询的键是类对象而非你指定的'blob_file_name',自然无法命中缓存,每次都会触发Blob读取。

2. 函数参数缺失

do_something_helper中调用get_blob_data_from_storage()时未传递file_name参数,而该方法定义明确要求传入文件名,这会引发参数错误(可能你实际代码中已补充,但当前提供的代码存在此问题)。

修复后的代码

修复cache.py

为类方法添加@staticmethod装饰器,确保参数传递正确:

class InMemoryCache:
    cache: dict = {}

    @staticmethod
    def get_cache(key):
        try:
            return InMemoryCache.cache[key]
        except KeyError:
            return None

    @staticmethod
    def set_cache(key, value):
        InMemoryCache.cache[key] = value

或者更简洁的方案:直接使用模块级别的缓存(无需类),避免类方法的复杂性:

# cache.py
_cache = {}

def get_cache(key):
    return _cache.get(key)

def set_cache(key, value):
    _cache[key] = value

修复do_something_helper.py

补充get_blob_data_from_storage的file_name参数:

from cache import InMemoryCache

def do_something_helper():
    blob_data = InMemoryCache.get_cache('blob_file_name')
    if blob_data:
        return blob_data

    # 传递文件名参数
    blob_data = get_blob_data_from_storage('blob_file_name')
    InMemoryCache.set_cache(key='blob_file_name', value=blob_data)
    return blob_data

额外注意事项

  • Azure Functions的内存缓存仅在同一实例进程内有效:当平台启动新实例回收旧实例时,缓存会丢失。如果需要跨实例共享缓存,建议使用Azure Redis Cache等分布式缓存方案。
  • 可以添加缓存过期逻辑:避免缓存数据长期失效,比如在缓存值中存储时间戳,查询时判断是否过期。

内容的提问来源于stack exchange,提问作者P V Ajay Thota

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 19:16:15