C# 怎么把Mysql查出来的数据存到缓存

时间:2026-02-15 20:39:30

1、在C#中,已经为我们提供了缓存的类型Cache,为了方便调用,我们需要自己重新封装。

2、第一步,新建CacheHelper类,用于存放我们封装的静态方法。

C# 怎么把Mysql查出来的数据存到缓存

3、第二步,封装添加缓存的方法。

public static void Add(string Key, object Value, CacheDependency dep = null, TimeSpan? Expires = null)

        {

            if (Value == null) return;

            if (Expires == null) Expires = TimeSpan.FromMinutes(30);

            // 设置缓存连续30分钟没有被访问则过期失效

            HttpRuntime.Cache.Insert(Key, Value, dep, Cache.NoAbsoluteExpiration, Expires.Value);

        }

C# 怎么把Mysql查出来的数据存到缓存

4、第三步,添加获取cache的方法。

 public static object Get(string Key)

        {

            return HttpRuntime.Cache.Get(Key);

        }

C# 怎么把Mysql查出来的数据存到缓存

5、第四步,将数据从mysql中读取出来,并存放在缓存中。

var res =mysql数据源;

sysUser = new Sys_User

{

    ID = res.data.user?.id,

    User_Name = res.data.user?.realname,

    User_Tel = res.data.user?.username,

    User_Email = res.data.user?.mail,

    IsAdmin = res.data.user?.userType == 1

};

//调用帮助类方法,存放缓存

CacheHelper.Add(cachKey, sysUser);

C# 怎么把Mysql查出来的数据存到缓存

6、第五步, 在将数据存放到缓存中,我们一般会先判断,缓存中是否已经存在此数据,如果有,则直接返回数据,如果没有,则从mysql中读取。到这里,我们就完成了将MySQL中查询出来的数据存入缓存并读取的功能。

 var cachKey = $"user_{userId}";

 var cacheValue = CacheHelper.Get(cachKey);

 if (cacheValue != null)

     return cacheValue as Sys_User;

C# 怎么把Mysql查出来的数据存到缓存

© 2026 手抄报圈
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com