C#连接Redis

**

第一步:nuget包——ServiceStack.Redis

**

public RedisCache _iCache = new RedisCache();
public void test(){
	string tokenKey = "";
	Token authToken = _iCache.Get(tokenKey);
            if (authToken == null)
            {
                authToken = new Token();
                authToken.SignToken = Guid.NewGuid().ToString().Replace("-", "");//设置token
                authToken.ExpireTime = DateTime.Now.AddDays(1);//过期时间值
                _iCache.Insert(tokenKey, authToken, authToken.ExpireTime);
            }
}
/// 
/// StackExchange Redis操作
/// 
public class RedisCache 
{
    int Default_Timeout = 600;//默认超时时间(单位秒)
    string address;
    JsonSerializerSettings jsonConfig = new JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore };
    ConnectionMultiplexer connectionMultiplexer;
    IDatabase database;

    class CacheObject
    {
        public int ExpireTime { get; set; }
        public bool ForceOutofDate { get; set; }
        public T Value { get; set; }
    }

    public RedisCache()
    {
        this.address = "==============连接地址===================";

        if (this.address == null || string.IsNullOrWhiteSpace(this.address.ToString()))
            throw new ApplicationException("配置文件中未找到RedisServer的有效配置");

        try
        {
            connectionMultiplexer = ConnectionMultiplexer.Connect(address);
            //RedisDBId
            int dbID = 0;
            database = connectionMultiplexer.GetDatabase(dbID);
        }
        catch (Exception)
        {
            throw new ApplicationException("连接异常");
        }
    }

    public RedisCache(string dbAddress, int dbID)
    {
        this.address = dbAddress;

        if (this.address == null || string.IsNullOrWhiteSpace(this.address.ToString()))
            throw new ApplicationException("Redis地址异常");
        connectionMultiplexer = ConnectionMultiplexer.Connect(address);
        database = connectionMultiplexer.GetDatabase(dbID);
    }

    /// 
    /// 连接超时设置
    /// 

你可能感兴趣的:(c#,redis)