public static bool Set(int db, string key, string? value, int s) { if (s == -1) { return redis.GetDatabase(db).StringSet(key, value); } else { TimeSpan dt = new TimeSpan(0, 0, s); return redis.GetDatabase(db).StringSet(key, value, dt); } }

当传入参数 s 为 -1 时,表示不设置缓存过期时间。上面的代码通过判断 s 的值,来选择调用 StringSet 方法的不同版本。

当 s 为 -1 时,代码调用不带过期时间参数的 StringSet 方法,实现不设置过期时间的功能。

代码解释:

  • db: 数据库索引
  • key: 缓存键
  • value: 缓存值
  • s: 过期时间,单位为秒。当 s 为 -1 时,表示不设置过期时间。

示例:

// 设置缓存,不设置过期时间
Set(0, "myKey", "myValue", -1);

// 设置缓存,过期时间为 10 秒
Set(0, "myKey", "myValue", 10);

注意:

  • 如果 s 为负数,但不是 -1,则会抛出异常。
  • 为了避免重复代码,可以考虑使用条件运算符简化代码。
  • 在实际应用中,需要根据具体需求选择合适的过期时间策略。
C# Redis 设置缓存并处理过期时间

原文地址: https://www.cveoy.top/t/topic/lw6F 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录