C# Redis 连接

前面我们已经准备成功开启Redis服务,其端口号为6379,接下来我们就看看如何使用C#语言来操作Redis。就如MongoDB一样,要操作Redis服务,自然就需要下载C#的客户端,这里通过Nuget下载了“ServiceStack.Redis”客户端,引入成功之后,就可以使用C#来对Redis服务进行操作了。

由于Redis一般是用来作为缓存的,也就是一般我们把一些不经常改变的数据通过Redis缓存起来,之后用户的请求就不需要再访问数据库,而可以直接从Redis缓存中直接获取,这样就可以减轻数据库服务器的压力以及加快响应速度。既然是用来做缓存的,也就是通过指定key值来把对应Value保存起来,之后再根据key值来获得之前缓存的值。具体的操作代码如下所示,这里就不过多介绍了。

请参考以下代码 -

class Program
    {
        static void Main(string[] args) { //在Redis中存储常用的5种数据类型:String,Hash,List,SetSorted set var client = new RedisClient("127.0.0.1", 6379); //AddString(client); //AddHash(client); //AddList(client); //AddSet(client); AddSetSorted(client); Console.ReadLine(); } private static void AddString(RedisClient client) { var timeOut = new TimeSpan(0,0,0,30); client.Add("Test", "Learninghard", timeOut); while (true) { if (client.ContainsKey("Test")) { Console.WriteLine("String Key: Test -Value: {0}, 当前时间: {1}", client.Get<string>("Test"), DateTime.Now); Thread.Sleep(10000); } else { Console.WriteLine("Value 已经过期了,当前时间:{0}", DateTime.Now); break; } } var person = new Person() {Name = "Learninghard", Age = 26}; client.Add("lh", person); var cachePerson = client.Get<Person>("lh"); Console.WriteLine("Person's Name is : {0}, Age: {1}", cachePerson.Name, cachePerson.Age); } private static void AddHash(RedisClient client) { if (client == null) throw new ArgumentNullException("client"); client.SetEntryInHash("HashId", "Name", "Learninghard"); client.SetEntryInHash("HashId", "Age", "26"); client.SetEntryInHash("HashId", "Sex", "男"); var hashKeys = client.GetHashKeys("HashId"); foreach (var key in hashKeys) { Console.WriteLine("HashId--Key:{0}", key); } var haskValues = client.GetHashValues("HashId"); foreach (var value in haskValues) { Console.WriteLine

转载于:https://www.cnblogs.com/zhangxiaoshuai/p/6482901.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值