C#下的redis第一个例子

本文介绍如何使用VS2010及C#进行Redis缓存操作,包括创建Redis操作类RedisCacheHelper,并实现缓存的添加、获取、删除等功能。通过示例演示了如何使用此类进行简单的缓存管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、使用VS2010开发,首先下载C#下用到的redis的dll,免费版的,下载链接如下

https://download.youkuaiyun.com/download/chencaw/10472019

2、创建一个Redis操作的公用类RedisCacheHelper

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
//using ServiceStack.Common.Extensions;
using ServiceStack.Redis;
using ServiceStack.Logging;


namespace chenredis1.RedisHelper
{
    class RedisCacheHelper
    {
        private static readonly PooledRedisClientManager pool = null;
        private static readonly string[] redisHosts = null;
       // public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);
      //  public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);
         public static int RedisMaxReadPool = 3;
         public static int RedisMaxWritePool = 1;
        static RedisCacheHelper()
        {
           // var redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];
            var redisHostStr = "127.0.0.1:6379";


            if (!string.IsNullOrEmpty(redisHostStr))
            {
                redisHosts = redisHostStr.Split(',');


                if (redisHosts.Length > 0)
                {
                    pool = new PooledRedisClientManager(redisHosts, redisHosts,
                        new RedisClientManagerConfig()
                        {
                            MaxWritePoolSize = RedisMaxWritePool,
                            MaxReadPoolSize = RedisMaxReadPool,
                            AutoStart = true
                        });
                }
            }
        }
        public static void Add<T>(string key, T value, DateTime expiry)
        {
            if (value == null)
            {
                return;
            }


            if (expiry <= DateTime.Now)
            {
                Remove(key);


                return;
            }


            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Set(key, value, expiry - DateTime.Now);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
            }


        }


        public static void Add<T>(string key, T value, TimeSpan slidingExpiration)
        {
            if (value == null)
            {
                return;
            }


            if (slidingExpiration.TotalSeconds <= 0)
            {
                Remove(key);


                return;
            }


            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Set(key, value, slidingExpiration);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
            }


        }






        public static T Get<T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return default(T);
            }


            T obj = default(T);


            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            obj = r.Get<T>(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", key);
            }




            return obj;
        }


        public static void Remove(string key)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Remove(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "删除", key);
            }


        }


        public static bool Exists(string key)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            return r.ContainsKey(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "是否存在", key);
            }


            return false;
        }
    }

}


4测试程序调用

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Redis写入缓存:zhong");
 
            RedisCacheHelper.Add("zhong""zhongzhongzhong", DateTime.Now.AddDays(1));
 
            Console.WriteLine("Redis获取缓存:zhong");
 
            string str3 = RedisCacheHelper.Get<string>("zhong");
 
            Console.WriteLine(str3);
 
            Console.WriteLine("Redis获取缓存:nihao");
            string str = RedisCacheHelper.Get<string>("nihao");
            Console.WriteLine(str);
 
 
            Console.WriteLine("Redis获取缓存:wei");
            string str1 = RedisCacheHelper.Get<string>("wei");
            Console.WriteLine(str1);
 
            Console.ReadKey();
        }
    }


5参考的blog

https://blog.youkuaiyun.com/zhulongxi/article/details/73604508


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值