【问题标题】:How do I call Redis StringSet() from F#如何从 F# 调用 Redis StringSet()
【发布时间】:2014-12-03 14:52:23
【问题描述】:

我正在使用 StackExchange.Redis 访问 Redis 实例。

我有以下可用的 C# 代码:

public static void Demo()
{
    ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("xxx.redis.cache.windows.net,ssl=true,password=xxx");

    IDatabase cache = connection.GetDatabase();

    cache.StringSet("key1", "value");
}

这是我希望的等效 F# 代码:

let Demo() =
   let cx = ConnectionMultiplexer.Connect @"xxx.redis.cache.windows.net,ssl=true,password=xxx"
   let cache = cx.GetDatabase()
   cache.StringSet("key1", "value") |> ignore

但是这不能编译 - '没有重载匹配方法 StringSet'。 StringSet 方法需要 RedisKey 和 RedisValue 类型的参数,并且 C# 中似乎有一些编译器魔法将调用代码中的字符串转换为 RedisKey 和 RedisValue。 F# 中似乎不存在这种魔法。有没有办法达到同样的效果?

【问题讨论】:

  • RedisKey.op_ImplicitRedisValue.op_Implicit 运算符吗?
  • @Daniel - 看起来像。如果我导航到定义,我会得到以下 .fsi 生成: type RedisKey = ... static member op_Implicit : key:string -> RedisKey static member op_Implicit : key:byte [] -> RedisKey static member op_Implicit : key:RedisKey -> byte [] 静态成员 op_Implicit : key:RedisKey -> string
  • 那么你需要做StringSet(RedisKey.op_Implicit "key1", RedisValue.op_Implicit "value")。这些是在 C# 中自动调用的,但不是 F#。你也可以define an "implicit" operator
  • 太棒了,看起来这会奏效。如果您将其发布为答案,我会将其标记为这样,并为您提供神奇的互联网积分。谢谢!
  • 我会亲自扩展字符串以拥有 toRedisKey 和 toRedisVal 的乐趣。更具可读性、可控性和清晰性。对 RedisKey 执行相同的操作以转换为字符串或其他任何内容。

标签: f# stackexchange.redis


【解决方案1】:

这是工作代码,非常感谢@Daniel:

open StackExchange.Redis
open System.Collections.Generic

let inline (~~) (x:^a) : ^b = ((^a or ^b) : (static member op_Implicit: ^a -> ^b) x)

let Demo() =
   let cx = ConnectionMultiplexer.Connect @"xxx.redis.cache.windows.net,ssl=true,password==xxx"
   let cache = cx.GetDatabase()

   // Setting a value - need to convert both arguments:
   cache.StringSet(~~"key1", ~~"value") |> ignore

   // Getting a value - need to convert argument and result:
   cache.StringGet(~~"key1") |> (~~) |> printfn "%s"

【讨论】:

  • 我有一个类似的问题我有一个字符串键和值,我想将它放入并从 redis 中取出 let searchToken = RedisKey.op_Implicit ("myKey" + token) let resultValue = cache. StringGet(searchToken) let redisData = RedisValue.op_Implicit(resultValue) 当我运行它时,我得到: 'RedisValue' 类型不支持转换为 ''a' 类型不知道我做错了什么。如何告诉 RedisValue.op_Implicit 它确实是一个字符串?
猜你喜欢
  • 2015-06-14
  • 2023-04-09
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多