【Redis】简易使用应用

Redis简介

  • Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
  • Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构
  • Redis支持数据的备份,即mater-slave模式的数据备份**

一、引入Nuget包

1.ServiceStack.Redis2.StackExchange.Redis

二、添加Redis配置文件

" RedisPath":" 127.0.0.1:6379"

三、导入封装好的工具类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;
namespace RedisDemo
{ 
	/// <summary> 
    /// RedisManager类主要是创建链接池管理对象的 
    /// </summary> 
    public class RedisManager 
    {  
        /// <summary>  
        /// redis配置文件信息  
        /// </summary>  
        private static string RedisPath = System.Configuration.ConfigurationSettings.AppSettings["RedisPath"];  
        private static PooledRedisClientManager _prcm;  
        /// <summary>  
        /// 静态构造方法,初始化链接池管理对象  
        /// </summary>  
        static RedisManager()  {   CreateManager();  }  
        /// <summary> 
        /// 创建链接池管理对象  
        /// </summary>  
        private static void CreateManager() 
        {  
            _prcm = CreateManager(new string[] { RedisPath }, new string[] { RedisPath }); 
        }  
        private static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts) 
        {   
            //WriteServerList:可写的Redis链接地址。   
            //ReadServerList:可读的Redis链接地址。   
            //MaxWritePoolSize:最大写链接数。   
            //MaxReadPoolSize:最大读链接数。  
            //AutoStart:自动重启。   
            //LocalCacheTime:本地缓存到期时间,单位:秒。  
            //RecordeLog:是否记录日志,该设置仅用于排查redis运行时出现的问题,如redis工作正常,请关闭该项。   
            //RedisConfigInfo类是记录redis连接信息,此信息和配置文件中的RedisConfig相呼应  
            // 支持读写分离,均衡负载  
            return new PooledRedisClientManager
                (readWriteHosts, readOnlyHosts, new RedisClientManagerConfig
                 {
                     MaxWritePoolSize = 5, 
                     // “写”链接池链接数    
                     MaxReadPoolSize = 5, 
                     // “读”链接池链接数    
                     AutoStart = true,   
                 }); 
        }  
        private static IEnumerable<string> SplitString(string strSource, string split)  
        {   
            return strSource.Split(split.ToArray()); 
        }  
        /// <summary>  
        /// 客户端缓存操作对象  
        /// </summary>  
        public static IRedisClient GetClient()  
        {  
            if (_prcm == null)  
            {   
                CreateManager();  
            }   
            return _prcm.GetClient();  
        } 
    }}

四、存储\读取操作

//获取Redis操作接口
IRedisClient Redis=RedisManager.GetClient();
//放入key,value
Redis.Set<string>("key","123");
//保存到硬盘
Redis.Save();
//释放内存
Redis.Dispose();
//读取数据
Redis.Get("key");

五、存入数据类型

stirng、int、double、byte……

如果是对象、结构数据可选择使用

(1).序列化对象为二进制(using Newtonsoft.Json;)

JsonConvert.SerializeObject(sokConnection);

(2).序列化为字符串

redis.get(string key);redis.set(string key,string value)

(3).转换对象为mapredis.hgetAll(string key);

redis.hmset(string key,Map<string,string> values);
六、应用**
实际应用液氮罐锁**
(1).超卖

 public class OversellTest 
 {    
     private static bool IsGoOn = true;
     //秒杀活动是否结束    
     public static void Show()   
     {     
         using (RedisStringService service = new RedisStringService())   
         {       
             service.Set<int>("Stock", 10);//是库存      
         }

         for (int i = 0; i < 5000; i++)    
         {        
             int k = i;      
             Task.Run(() =>//每个线程就是一个用户请求       
                      {         
                          using (RedisStringService service = new RedisStringService())         
                          {           
                              if (IsGoOn)          
                              {              
                                  long index = service.Decr("Stock");//-1并且返回              
                                  if (index >= 0)             
                                  {               
                                      Console.WriteLine($"{k.ToString("000")}秒杀成功,秒杀商品索引为{index}");                
                                      //service.Incr("Stock");//+1            
                                      //可以分队列,去数据库操作         
                                  }            
                                  else              
                                  {              
                                      if (IsGoOn)     
                                      {                 
                                          IsGoOn = false;    
                                      }                
                                      Console.WriteLine($"{k.ToString("000")}秒杀失败,秒杀商品索引为{index}");             
                                  }        
                              }           
                              else         
                              {             
                                  Console.WriteLine($"{k.ToString("000")}秒杀停止......");  
                              }       
                          }       
                      });     
         }      
         Console.Read(); 
     } 
 }

(2).实时排行

/// <summary>  
/// 实时排行榜:刷个礼物  
/// 维度很多,平台/房间/主播/日/周/月/年 
/// A对B 刷个礼物,影响很多 
/// 刷礼物只记录流水,不影响排行,凌晨24点跑任务更新 
///  
/// 实时排行榜  
/// Redis-IncrementItemInSortedSet 
/// 刷礼物时增加redis分数 
/// 就可以实时获取最新的排行 
/// (多个维度就是多个zSet,刷礼物的时候保存数据库并更新Redis) 
/// </summary>  
public class RankManager 
{   
    private static List<string> UserList = new List<string>()  
    {      "Tenk","花生","Ray","阿莫西林","石昊","ywa"    };   
    public static void Show()   
    {      
        using (RedisZSetService service = new RedisZSetService())  
        {      
            service.FlushAll();//清理全部数据

            Task.Run(() =>       
                     {      
                         while (true)  
                         {           
                             foreach (var user in UserList)       
                             {           
                                 Thread.Sleep(10);     
                                 service.IncrementItemInSortedSet("陈一发儿", user, new Random().Next(1, 100));//表示在原来刷礼物的基础上增加礼物        
                             }           
                             Thread.Sleep(20 * 1000);     
                         }     
                     });
            Task.Run(() =>      
                     {       
                         while (true)        
                         {         
                             Thread.Sleep(12 * 1000);      
                             Console.WriteLine("**********当前排行************");    
                             int i = 1;
    foreach (var item in service.GetAllWithScoresFromSortedSet("陈一发儿"))    
    {             
        Console.WriteLine($"第{i++}名 {item.Key} 分数{item.Value}");   
    }           
                             //foreach (var item in service.GetAllDesc("陈一发儿"))      
                             //{          
                             //  Console.WriteLine($"第{i++}名 {item}");    
                             //}        
                         }       
                     });

            Console.Read();

        }

    } 
}
posted @ 2022-03-28 08:01  Yan-X  阅读(80)  评论(0)    收藏  举报