我是Redis的新手(在托管服务中使用它),并希望将其用作列表的演示/沙箱数据存储。
我使用下面的代码。这个对我有用。但对于一个拥有多个(最多100个)并发用户(对于少量数据 - 最多1000个列表项)的小型网站来说,这是一种有效(而非完全不好的做法)用法吗?
我正在使用静态连接和静态redisclient类型列表,如下所示:
public class MyApp
{
private static ServiceStack.Redis.RedisClient redisClient;
public static IList<Person> Persons;
public static IRedisTypedClient<Person> PersonClient;
static MyApp()
{
redisClient = new RedisClient("nnn.redistogo.com", nnn) { Password = "nnn" };
PersonClient = redisClient.GetTypedClient<Person>();
Persons = PersonClient.Lists["urn:names:current"];
}
}
这样做我有一个非常容易使用的持久数据列表,这正是我在构建/演示应用程序的基本块时所需要的。
foreach (var person in MyApp.Persons) ...
添加新人:
MyApp.Persons.Add(new Person { Id = MyApp.PersonClient.GetNextSequence(), Name = "My Name" });
我担心(目前)不是我在appstart上将完整列表加载到内存中的事实,而是我与redis主机的连接不遵循良好标准的可能性 - 或者是否存在其他问题我不是意识到。
谢谢
实际上当你使用 PersonClient.Lists["urn:names:current"]
您实际上存储了对线程安全的RedisClient连接的引用。如果它在GUI或Console应用程序中,则可以,但在多线程Web应用程序中并不理想。在大多数情况下,您希望使用线程安全连接工厂,即
var redisManager = new PooledRedisClientManager("localhost:6379");
其行为非常类似于数据库连接池。因此,每当您想要访问RedisClient时,工作方式如下:
using (var redis = redisManager.GetClient())
{
var allItems = redis.As<Person>().Lists["urn:names:current"].GetAll();
}
注意: .As<T>
是一个较短的别名 .GetTypedClient<T>
从redisManager执行类型化客户端的另一个方便的快捷方式是:
var allItems = redisManager.ExecAs<Person>(r => r.Lists["urn:names:current"].GetAll());
我通常喜欢传球 IRedisClientsManager
在我的代码中,因此它不包含RedisClient连接,但可以在需要时访问它。
实际上当你使用 PersonClient.Lists["urn:names:current"]
您实际上存储了对线程安全的RedisClient连接的引用。如果它在GUI或Console应用程序中,则可以,但在多线程Web应用程序中并不理想。在大多数情况下,您希望使用线程安全连接工厂,即
var redisManager = new PooledRedisClientManager("localhost:6379");
其行为非常类似于数据库连接池。因此,每当您想要访问RedisClient时,工作方式如下:
using (var redis = redisManager.GetClient())
{
var allItems = redis.As<Person>().Lists["urn:names:current"].GetAll();
}
注意: .As<T>
是一个较短的别名 .GetTypedClient<T>
从redisManager执行类型化客户端的另一个方便的快捷方式是:
var allItems = redisManager.ExecAs<Person>(r => r.Lists["urn:names:current"].GetAll());
我通常喜欢传球 IRedisClientsManager
在我的代码中,因此它不包含RedisClient连接,但可以在需要时访问它。