1. 程式人生 > >Redis C#緩存的使用

Redis C#緩存的使用

multipl redis tip gets 消息 change 通道 red strings

原文:Redis C#緩存的使用

一、下載第三方類庫:StackExchange.Redis

  Nuget收索StackExchange.Redis,點擊安裝即可,新增的第三方命名空間:using StackExchange.Redis;

二、StackExchange.Redis使用(使用前提是有Redis服務端:Linux Redis的安裝可查看此文):

  1、鍵值的存取:

static void Noth(string[] args)
        {
            string host = "192.168.117.129";
            ConnectionMultiplexer redis 
= ConnectionMultiplexer.Connect(host); IDatabase db = redis.GetDatabase(); db.StringSet("User", "{name:\"TOM\"}"); db.StringAppend("User", ",{name:\"JACK\"}"); string user = db.StringGet("User"); Console.WriteLine(user); Console.Read(); }

2、事件的訂閱:

  發布端代碼:

  

static void Main(string[] args)
        {
            string host = "192.168.117.129";
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(host);
            ISubscriber db = redis.GetSubscriber();
            db.Publish("c1", "123");
            
string reader="start end"; while (reader != "exit") { reader = Console.ReadLine(); db.Publish("c1", reader); } Console.Read(); }

訂閱者代碼:

static void Main(string[] args)
        {
            string host = "192.168.117.129";
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(host);
            ISubscriber db = redis.GetSubscriber();
            db.Subscribe("c1",new Action<RedisChannel,RedisValue>((chan,msage)=>{
                Console.WriteLine("通道:"+chan);
                Console.WriteLine("消息內容:"+msage);
            }));
            Console.ReadLine();
        }

Redis C#緩存的使用