C# 通过ServiceStack 操作Redis

这篇文章主要介绍了C# 通过ServiceStack 操作Redis的示例,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下

作       者 : 明志德道

1.引用Nuget包 ServiceStack.Redis

我这里就用别人已经封装好的Reids操作类来和大家一起参考了下,看看怎么使用ServiceStack.Redis 操作Redis数据

RedisConfigInfo--redis配置文件信息


 /// <summary>
 /// redis配置文件信息
 /// 也可以放到配置文件去
 /// </summary>
 public sealed class RedisConfigInfo
 {
  /// <summary>
  /// 可写的Redis链接地址
  /// format:ip1,ip2
  /// 
  /// 默认6379端口
  /// </summary>
  public string WriteServerList = "127.0.0.1:6379";
  /// <summary>
  /// 可读的Redis链接地址
  /// format:ip1,ip2
  /// </summary>
  public string ReadServerList = "127.0.0.1:6379";
  /// <summary>
  /// 最大写链接数
  /// </summary>
  public int MaxWritePoolSize = 60;
  /// <summary>
  /// 最大读链接数
  /// </summary>
  public int MaxReadPoolSize = 60;
  /// <summary>
  /// 本地缓存到期时间,单位:秒
  /// </summary>
  public int LocalCacheTime = 180;
  /// <summary>
  /// 自动重启
  /// </summary>
  public bool AutoStart = true;
  /// <summary>
  /// 是否记录日志,该设置仅用于排查redis运行时出现的问题,
  /// 如redis工作正常,请关闭该项
  /// </summary>
  public bool RecordeLog = false;
 }

RedisManager --Redis管理中心   创建Redis链接


 /// <summary>
 /// Redis管理中心 创建Redis链接
 /// </summary>
 public class RedisManager
 {
  /// <summary>
  /// redis配置文件信息
  /// </summary>
  private static RedisConfigInfo RedisConfigInfo = new RedisConfigInfo();

  /// <summary>
  /// Redis客户端池化管理
  /// </summary>
  private static PooledRedisClientManager prcManager;

  /// <summary>
  /// 静态构造方法,初始化链接池管理对象
  /// </summary>
  static RedisManager()
  {
   CreateManager();
  }

  /// <summary>
  /// 创建链接池管理对象
  /// </summary>
  private static void CreateManager()
  {
   string[] WriteServerConStr = RedisConfigInfo.WriteServerList.Split(',');
   string[] ReadServerConStr = RedisConfigInfo.ReadServerList.Split(',');
   prcManager = new PooledRedisClientManager(ReadServerConStr, WriteServerConStr,
        new RedisClientManagerConfig
        {
         MaxWritePoolSize = RedisConfigInfo.MaxWritePoolSize,
         MaxReadPoolSize = RedisConfigInfo.MaxReadPoolSize,
         AutoStart = RedisConfigInfo.AutoStart,
        });
  }

  /// <summary>
  /// 客户端缓存操作对象
  /// </summary>
  public static IRedisClient GetClient()
  {
   return prcManager.GetClient();
  }
 }

RedisBase-- 是redis操作的基类,继承自IDisposable接口,主要用于释放内存


/// <summary>
 /// RedisBase类,是redis操作的基类,继承自IDisposable接口,主要用于释放内存
 /// </summary>
 public abstract class RedisBase : IDisposable
 {
  public IRedisClient iClient { get; private set; }
  /// <summary>
  /// 构造时完成链接的打开
  /// </summary>
  public RedisBase()
  { 
   iClient = RedisManager.GetClient();
  }

  //public static IRedisClient iClient { get; private set; }
  //static RedisBase()
  //{
  // iClient = RedisManager.GetClient();
  /

本文标题为:C# 通过ServiceStack 操作Redis

基础教程推荐