Is this a valid usage of ServiceStack Redis?

后端 未结 2 1498
时光说笑
时光说笑 2020-12-14 11:55

I am new to Redis (using it at a hosted service) and want to use it as a demonstration / sandbox data storage for lists.

I use the following piece of code. It works

相关标签:
2条回答
  • 2020-12-14 12:11

    Actually when you use PersonClient.Lists["urn:names:current"] you're actually storing a reference to a RedisClient Connection which is not thread safe. It's ok if it's in a GUI or Console app, but not ideal in a multi-threaded web app. In most scenarios you want to be using a thread safe connection factory i.e.

    var redisManager = new PooledRedisClientManager("localhost:6379");
    

    Which acts very much like a database connection pool. So whenever you want to access the RedisClient works like:

    using (var redis = redisManager.GetClient())
    {
        var allItems = redis.As<Person>().Lists["urn:names:current"].GetAll();
    }
    

    Note: .As<T> is a shorter alias for .GetTypedClient<T> Another convenient short-cut to execute a typed client from a redisManager is:

    var allItems = redisManager.ExecAs<Person>(r => r.Lists["urn:names:current"].GetAll());
    

    I usually prefer to pass around IRedisClientsManager in my code so it doesn't hold a RedisClient connection but can access it whenever it needs to.

    0 讨论(0)
  • 2020-12-14 12:17

    There is an example project here

    0 讨论(0)
提交回复
热议问题