前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Redis从入门到精通(二)C#中使用redis及封装Redis工具类

Redis从入门到精通(二)C#中使用redis及封装Redis工具类

作者头像
架构师精进
发布2020-05-24 14:53:15
8.6K0
发布2020-05-24 14:53:15
举报

上一篇讲述了安装redis《Redis总结(一)Redis安装》,同时也大致介绍了redis的优势和应用场景。本篇着重讲解.NET中如何使用redis和C#。

Redis官网提供了很多开源的C#客户端。例如,Nhiredis ,ServiceStack.Redis ,StackExchange.Redis等。其中ServiceStack.Redis应该算是比较流行的。它提供了一整套从Redis数据结构都强类型对象转换的机制并将对象json序列化。所以这里只介绍ServiceStack.Redis,它也是目前我们产品中所使用的客户端。

一、ServiceStack.Redis地址:https://github.com/ServiceStack/ServiceStack.Redis

二、快速上手

1、 建立一个控制台应用程序,并引用以下ServiceStack.Redis相关的四个类库。或者通过Nuget进行安装Redis常用组件ServiceStack.Redis。 下载示例代码。

2、创建Redis 客户端


protected RedisClient Redis = new RedisClient("127.0.0.1", 6379);//redis服务IP和端口

3、存储、读取缓存数据

UserInfo数据实体定义:


public class UserInfo
 {
        public long Id { set; get; }
        public string UserName { get; set; }
        public int Age { get; set; }
}

存储、获取对象

  // 存储对象
  Redis.Set<UserInfo>("userinfo", new UserInfo() { UserName = "李四", Age = 45 });
  // 获取缓存对象
  UserInfo userinfo = Redis.Get<UserInfo>("userinfo");

redis 底层使用json序列化。将对象序列号成json数据格式存储。

三、封装

在我们实际的使用Redis的过程中,肯定不能在每个调用的类都实例化 RedisClient 来直接使用,这样太麻烦,还涉及相关异常情况处理等情况。一般是将操作Redis的相关方法封装成通用的工具类,提供给调用方使用。

1、创建一个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 Weiz.Redis.RedisTest
{
    public 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"]);
 
        static RedisCacheHelper()
        {
            var redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];
 
            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;
        }
    }
}

说明:RedisCacheHelper 使用的是客户端链接池模式,这样的存取效率应该是最高的。同时也更方便的支持读写分离,均衡负载。

2、配置文件

在配置文件中,增加Redis服务器相关的配置,如host,pool等参数。

<!-- redis Start   -->
<add key="SessionExpireMinutes" value="180" />
<add key="redis_server_session" value="127.0.0.1:6379" />
<add key="redis_max_read_pool" value="3" />
<add key="redis_max_write_pool" value="1" />
<!--redis end-->

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();
        }
    }

以上就把C# 中redis的使用与封装介绍完了,是不是特别简单。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-05-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 架构师精进 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档