当开始用    var result=new RedisClient("127.0.0.1",6379,1"1111");  这个helper ,后面有并发之后就一直提示超时问题。

后面改为连接池(集群的方式)

/// <summary>
/// 连接客户端管理
/// </summary>
private static PooledRedisClientManager prcm;

/// <summary>
/// 创建链接池管理对象
/// </summary>
public static PooledRedisClientManager CreateManager()
{
string[] writeServerList = SplitString(redisConfigInfo.WriteServerList, ",");
string[] readServerList = SplitString(redisConfigInfo.ReadServerList, ",");

return new PooledRedisClientManager(writeServerList, readServerList,
new RedisClientManagerConfig
{
MaxWritePoolSize = redisConfigInfo.MaxWritePoolSize,
MaxReadPoolSize = redisConfigInfo.MaxReadPoolSize,
DefaultDb = redisConfigInfo.InitalDb,
AutoStart = redisConfigInfo.AutoStart,
}); //, redisConfigInfo.InitalDb
}

/// <summary>
/// 客户端缓存操作对象
/// </summary>
public static IRedisClient GetClient()
{
if (OpenRedis)
{
if (prcm == null)
{
 prcm = CreateManager();
}

return prcm.GetClient();
}
return null;
}

但发现用同一个还是连接池并发大还是有问题,从日志上面看

Redis Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use.
异常信息:System.TimeoutException: Redis Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use.

could not connect to redis Instance at 127.0.0.1:6379
异常信息:ServiceStack.Redis.RedisException: could not connect to redis Instance at 127.0.0.1:6379 ---> System.Net.Sockets.SocketException: 在一个非套接字上尝试了一个操作。 127.0.0.1:6379

后面在网上查找的时候看到使用using 的方法。 跟连接数据库一样的道理,还有开多线程会报错,要加local锁

RedisConfigInfo类

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;

namespace Cache.Redis
{
/// <summary>
/// 获取redis配置的类
/// </summary>
public sealed class RedisConfigInfo:ConfigurationSection
{
public static RedisConfigInfo GetConfig()
{
var section = (RedisConfigInfo)System.Configuration.ConfigurationManager.GetSection("RedisConfig");
return section;
}
public static RedisConfigInfo GetConfig(string sectionName)
{
var section = (RedisConfigInfo)ConfigurationManager.GetSection("RedisConfig");
if (section == null)
{
throw new ConfigurationErrorsException("Section " + sectionName + " is not found.");
}
return section;
}

/// <summary>
/// 可写的Redis链接地址
/// </summary>
[ConfigurationProperty("WriteServerList", IsRequired = false)]
public string WriteServerList
{
get
{
return (string)base["WriteServerList"];
}

set {
base["WriteServerList"] = value;
}
}

/// <summary>
/// 可读的Redis链接地址,它一般由多个服务器组件,一般称为从服务器(slave),各个服务器之间用逗号分开
/// </summary>
[ConfigurationProperty("ReadServerList", IsRequired = false)]
public string ReadServerList
{
get
{
return (string)base["ReadServerList"];
}

set
{
base["ReadServerList"] = value;
}
}

/// <summary>
/// 最大写链接数
/// </summary>
[ConfigurationProperty("MaxWritePoolSize", IsRequired = false, DefaultValue = 5)]
public int MaxWritePoolSize
{
get
{
return (int)base["MaxWritePoolSize"];
}

set
{
base["MaxWritePoolSize"] = value;
}
}

/// <summary>
/// 初始化哪个库
/// </summary>
[ConfigurationProperty("InitalDb", IsRequired = false)]
public long InitalDb
{
get
{
return (long)base["InitalDb"];
}

set
{
base["InitalDb"] = value;
}
}

/// <summary>
/// 最大写链接数
/// </summary>
[ConfigurationProperty("MaxReadPoolSize", IsRequired = false, DefaultValue = 5)]
public int MaxReadPoolSize
{
get
{
return (int)base["MaxReadPoolSize"];
}

set
{
base["MaxReadPoolSize"] = value;
}
}

/// <summary>
/// 自动重启
/// </summary>
[ConfigurationProperty("AutoStart", IsRequired = false, DefaultValue = true)]
public bool AutoStart
{
get
{
return (bool)base["AutoStart"];
}

set
{
base["AutoStart"] = value;
}
}

/// <summary>
/// 本地缓存到期时间,单位:秒
/// </summary>
[ConfigurationProperty("LocalCacheTime", IsRequired = false, DefaultValue = 36000)]
public int LocalCacheTime
{
get
{
return (int)base["LocalCacheTime"];
}

set
{
base["LocalCacheTime"] = value;
}
}

/// <summary>
/// 是否记录日志,该设置仅用于排查redis运行时出现的问题,如redis工作正常,请关闭该项
/// </summary>
[ConfigurationProperty("RecordeLog", IsRequired = false, DefaultValue = false)]
public bool RecordeLog
{
get
{
return (bool)base["RecordeLog"];
}

set
{
base["RecordeLog"] = value;
}
}

/// <summary>
/// 超时时间
/// </summary>
[ConfigurationProperty("PoolTimeOutSeconds", IsRequired = false, DefaultValue = 5000)]
public int PoolTimeOutSeconds
{
get
{
return (int)base["PoolTimeOutSeconds"];
}

set
{
base["PoolTimeOutSeconds"] = value;
}
}

}
}

RedisOperatorBase类

using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Cache.Redis
{
/// <summary>
/// Redis回收类
/// </summary>
public abstract class RedisOperatorBase : IDisposable
{
protected static object lockobj = new object();

private bool _disposed = false;
protected RedisOperatorBase()
{
}
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
}
}
this._disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// 保存数据DB文件到硬盘
/// </summary>
public void Save()
{
}
/// <summary>
/// 异步保存数据DB文件到硬盘
/// </summary>
public void SaveAsync()
{
}

}
}

RedisManager  redis管理的类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;

namespace Cache.Redis
{
/// <summary>
/// redis管理的类
/// </summary>
public class RedisManager
{
public static bool OpenRedis = System.Configuration.ConfigurationManager.AppSettings["OpenRedis"] == null ? false : Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["OpenRedis"]);
/// <summary>
/// redis配置文件信息
/// </summary>
private static RedisConfigInfo redisConfigInfo = RedisConfigInfo.GetConfig();

/// <summary>
/// 创建链接池管理对象
/// </summary>
public static PooledRedisClientManager CreateManager()
{
string[] writeServerList = SplitString(redisConfigInfo.WriteServerList, ",");
string[] readServerList = SplitString(redisConfigInfo.ReadServerList, ",");

return new PooledRedisClientManager(writeServerList, readServerList,
new RedisClientManagerConfig
{
MaxWritePoolSize = redisConfigInfo.MaxWritePoolSize,
MaxReadPoolSize = redisConfigInfo.MaxReadPoolSize,
DefaultDb = redisConfigInfo.InitalDb,
AutoStart = redisConfigInfo.AutoStart,
}); //, redisConfigInfo.InitalDb
}

/// <summary>
/// 得到连接数组
/// </summary>
/// <param name="strSource"></param>
/// <param name="split"></param>
/// <returns></returns>

private static string[] SplitString(string strSource, string split)
{
return strSource.Split(split.ToArray());
}

}
}

Redis string get set的类

using ServiceStack.Redis;
using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Cache.Redis
{
/// <summary>
/// redis的string
/// </summary>
public class RedisStringOperator : RedisOperatorBase
{

public RedisStringOperator() : base() { }
/// <summary>
///redis的string 存值
/// </summary>
public bool Set<T>(string key, T t)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return true;
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.Set(key, t);
}
}

}

/// <summary>
/// redis的string存值
/// </summary>
public bool Set<T>(string key, T t, DateTime expiresAt)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return true;
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.Set(key, t, expiresAt);
}
}

//return Redis.Set(key, t, expiresAt);
}

/// <summary>
/// 存值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public bool Set(string key, string value)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return true;
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.Set<string>(key, value);
}
}

}
/// <summary>
/// 移除
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Remove(string key)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return true;
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.Remove(key);
}
}
}
/// <summary>
/// 取值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T Get<T>(string key)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return default(T);
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.Get<T>(key);
}
}

}

/// <summary>
/// 设置缓存过期
/// </summary>
public bool SetExpire(string key, DateTime datetime)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return true;
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.ExpireEntryAt(key, datetime);
}
}
}

}
}

RedisHash的类

using ServiceStack.Text;
using System;
using System.Collections.Generic;

namespace Cache.Redis
{
public class RedisHashOperator : RedisOperatorBase
{
public RedisHashOperator() : base() { }
/// <summary>
/// 判断某个数据是否已经被缓存
/// </summary>
public bool ExistHashContainsEntry(string hashId, string key)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return true;
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.HashContainsEntry(hashId, key);
}
}
}
/// <summary>
/// 存储数据到hash表
/// </summary>
public bool SetInHash<T>(string hashId, string key, T t)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return true;
}
var value = JsonSerializer.SerializeToString<T>(t);
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.SetEntryInHash(hashId, key, value);
}
}
}

/// <summary>
/// 存储数据到hash表
/// </summary>
/// <param name="hashId"></param>
/// <param name="key"></param>
/// <param name="t"></param>
/// <returns></returns>
public bool SetInHash(string hashId, string key, string value)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return true;
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.SetEntryInHash(hashId, key, value);
}
}
}

/// <summary>
/// 移除hash中的某值
/// </summary>
public bool RemoveFromHash(string hashId, string key)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return true;
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.RemoveEntryFromHash(hashId, key);
}
}
}
///// <summary>
///// 移除整个hash
///// </summary>
//public static bool Remove(string key)
//{
// return Redis.Remove(key);
//}

/// <summary>
/// 从hash表获取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="hashId"></param>
/// <param name="key"></param>
/// <returns></returns>
public T GetFromHash<T>(string hashId, string key)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return default(T);
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
string value = redieclient.GetValueFromHash(hashId, key);
return JsonSerializer.DeserializeFromString<T>(value);
}
}

//string value = Redis.GetValueFromHash(hashId, key);
//return JsonSerializer.DeserializeFromString<T>(value);
}

/// <summary>
/// 从hash表获取数据
/// </summary>
/// <param name="hashId"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetFromHash(string hashId, string key)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return "";
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.GetValueFromHash(hashId, key);
}
}
}

/// <summary>
/// 获取整个hash的数据
/// </summary>
public static List<T> GetAllFromHash<T>(string hashId)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return new List<T>();
}
var result = new List<T>();
lock (lockobj)
{

using (var redieclient = RedisManager.CreateManager().GetClient())
{
var list = redieclient.GetHashValues(hashId);
if (list != null && list.Count > 0)
{
list.ForEach(x =>
{
var value = JsonSerializer.DeserializeFromString<T>(x);
result.Add(value);
});
}

}
}
return result;
}

/// <summary>
/// 根据hash获取keys
/// </summary>
/// <param name="hashId"></param>
/// <returns></returns>
public static List<string> GetHashKeys(string hashId)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return new List<string>();
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.GetHashKeys(hashId);
}
}
}

/// <summary>
/// 获取整个hash的数据
/// </summary>
public static List<string> GetAllFromHash(string hashId)
{
if (!Cache.Redis.RedisManager.OpenRedis)
{
return new List<string>();
}
lock (lockobj)
{
using (var redieclient = RedisManager.CreateManager().GetClient())
{
return redieclient.GetHashValues(hashId);
}
}

}

}
}

比如string的set方法

<configSections>
<!--redis缓存-->
<section name="RedisConfig" type="Cache.Redis.RedisConfigInfo,Cache" />
</configSections>
<!--ServiceStack.Redis 4.0以后的版本的格式 password@IP:port?&db=1&ssl=true&client=aaa&password=123&namespaceprefix=vvv&connecttimeout=10&sendtimeout=10&receivetimeout=10&retrytimeout=10&idletimeout=10-->
<!--redis缓存 写入地址(如果没有密码则不用@以及@之前的值,如127.0.0.1:6379,有密码则51sole@127.0.0.1:6379) 读的地址 默认数据库是第几个 最大超时时间(秒) 最大写链接数 最大读的链接数 是否自动重启 缓存时间 是否写入日志 -->
<RedisConfig WriteServerList="127.0.0.1:6379" ReadServerList="127.0.0.1:6379" InitalDb="3" PoolTimeOutSeconds="5000" MaxWritePoolSize="5" MaxReadPoolSize="5" AutoStart="true" LocalCacheTime="180" RecordeLog="false">
</RedisConfig>

string的 get 和set方法

//
// GET: /RedisTest/
public ActionResult Index()
{
Cache.Redis.RedisStringOperator redistring = new Cache.Redis.RedisStringOperator();
redistring.Set("test", 1);
return View();
}

public ActionResult GetRedisValue()
{
Cache.Redis.RedisStringOperator redistring = new Cache.Redis.RedisStringOperator();
redistring.Get<int>("test");
}

asp.net redis 实战的更多相关文章

  1. C# Redis实战

    转自  :http://blog.csdn.net/qiujialongjjj/article/details/16945569 一.初步准备 Redis 是一个开源的使用ANSI C 语言编写.支持 ...

  2. C# Redis实战(三)

    三.程序配置 在C# Redis实战(二)中我们安装好了Redis的系统服务,此时Redis服务已经运行. 现在我们需要让我们的程序能正确读取到Redis服务地址等一系列的配置信息,首先,需要在Web ...

  3. ASP.NET Core 实战:基于 Dapper 扩展你的数据访问方法

    一.前言 在非静态页面的项目开发中,必定会涉及到对于数据库的访问,最开始呢,我们使用 Ado.Net,通过编写 SQL 帮助类帮我们实现对于数据库的快速访问,后来,ORM(Object Relatio ...

  4. ASP.NET Core 实战:基于 Jwt Token 的权限控制全揭露

    一.前言 在涉及到后端项目的开发中,如何实现对于用户权限的管控是需要我们首先考虑的,在实际开发过程中,我们可能会运用一些已经成熟的解决方案帮助我们实现这一功能,而在 Grapefruit.VuCore ...

  5. ASP.NET Core 实战:将 .NET Core 2.0 项目升级到 .NET Core 2.1

    一.前言  最近一两个星期,加班,然后回去后弄自己的博客,把自己的电脑从 Windows 10 改到 Ubuntu 18.10 又弄回 Windows 10,原本计划的学习 Vue 中生命周期的相关知 ...

  6. Redis实战阅读笔记——开始

    Redis实战这本书,看完以后最大的不是redis本身的东西,而是作者面对实际问题的分析而给出的设计方案,可以看成NoSql设计的应用.个人从这方面收获很多,至于Redis本身的东西,这个就花一两个小 ...

  7. Redis实战阅读笔记——第一章

    Redis 实战 中文版 的20-21页看的人郁闷死了,最后看英文版才明白意思,哎,我理解能力差成这样了 其中,图 1-12 有错误,草,这个是英文版的错--应该是group:programming

  8. redis实战(01)_redis安装

    早就想对redis进行实战操作了,最近看了一些视频和参考书籍,总结总结一下,redis实战内容: 实战前先对redis做一个大概的认识: 现在开始安装redis了... redis的安装下载地址 ht ...

  9. ASP开发入门+实战电子书共50本 —下载目录

    小弟为大家整理50个ASP电子书籍,有入门,也有实战电子书,做成了一个下载目录,欢迎大家下载. 资源名称 资源地址 ASP.NET开发实战1200例_第I卷 http://down.51cto.com ...

随机推荐

  1. JS获取IP、MAC和主机名的五种方法

    javascript获取客户端IP的小程序,下面的代码是我在所有windowsNT5.0及以上的系统上都测试通过的,喜欢的朋友可以收藏下.今天在搞JS(javascript)获取客户端IP的小程序,上 ...

  2. 《Excel图表之道》读书笔记

    一.突破常规的作图方法 突破Excel的默认颜色 非数据元素用淡色 突破Excel的图表布局 图表要素:主标题.副标题.图例.绘图.脚注 竖向构图 标明数据来源.图表注释.坐标轴截断符号 专业的水蓝色 ...

  3. eclipse中DDMS的LOGcat只有一列level

    拷贝来源:http://www.cnblogs.com/kobe8/p/4620785.html http://stackoverflow.com/questions/25010393/eclipse ...

  4. Mongoengine 使用笔记

    1.直接将某个document对象导出对应的json数据. #models class Feed(Document): """ @summary: 所有订阅内容 &quo ...

  5. Memcached(二)Memcached Java API基础之MemcachedClient

    1. 构造函数 public MemcachedClient(InetSocketAddress[] ia) throws IOException; public MemcachedClient(Li ...

  6. Firebird/InterBase内置函数使用说明

    Firebird/InterBase内置函数使用说明(转自:圣域天堂) 2008-10-12 20:56 加*号为FB2.0加入的函数 整理:剑雷(jianlei) 2006-10-13 1. COU ...

  7. 设置UIButton的文字居右显示 去掉点击默认置灰效果

    1.设置UIButton的文字居右显示 [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight]; ...

  8. 第 6 章 抽象工厂模式【Abstract Factory Pattern】

    以下内容出自:<<24种设计模式介绍与6大设计原则>> 好了,我们继续上一节课,上一节讲到女娲造人,人是造出来了,世界时热闹了,可是低头一看,都 是清一色的类型,缺少关爱.仇恨 ...

  9. poi 操作excel

    poi操作 创建一个excel关联对象HSSFWorkbook: HSSFWorkbook book = new HSSFWorkbook(); 创建一个sheet: HSSFSheet st = b ...

  10. 再探CRC

    之前写了CRC16的程序,虽说能用,却不知其所心然,现在要用CRC32,重温一遍,一下就通了.笔记如下 CRC我没记错的话是Cyclic Redundancy Code,Cyclic和Redundan ...