Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call Redis StringSet() from F#

I am using StackExchange.Redis to access a Redis instance.

I have the following working C# code:

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");
}

Here is the what I would hope would be the equivalent F# code:

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

However this does not compile - 'No overloads match for method StringSet'. The StringSet method expects arguments of type RedisKey and RedisValue, and there seems to be some compiler magic going on in C# to convert the strings in the calling code into RedisKey and RedisValue. The magic does not appear to exist in F#. Is there a way of achieving the same result?

like image 349
Kit Avatar asked Dec 03 '14 14:12

Kit


People also ask

What is Redis ConnectionMultiplexer?

Redis is the ConnectionMultiplexer class in the StackExchange. Redis namespace; this is the object that hides away the details of multiple servers. Because the ConnectionMultiplexer does a lot, it is designed to be shared and reused between callers. You should not create a ConnectionMultiplexer per operation.

What is StackExchange Redis?

Overview. StackExchange. Redis is a high performance general purpose redis client for . NET languages (C#, etc.). It is the logical successor to BookSleeve, and is the client developed-by (and used-by) Stack Exchange for busy sites like Stack Overflow.

What is lazy ConnectionMultiplexer?

It uses Lazy<T> to handle thread-safe initialization. It sets "abortConnect=false", which means if the initial connect attempt fails, the ConnectionMultiplexer will silently retry in the background rather than throw an exception.


Video Answer


1 Answers

Here is the working code, many thanks to @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"
like image 95
Kit Avatar answered Nov 15 '22 01:11

Kit