C# Redis 使用:
Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。
使用的数据驱动是:stackexchange.可以从NUGET中安装。
1)加载配置
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommonTool.Redis
{
public static class RedisConnectionHelp
{
public static readonly string SysCustomKey = ConfigurationManager.AppSettings["redisKey"] ?? "";
//"127.0.0.1:6379,password=****"
private static readonly string RedisConnectionString = ConfigurationManager.ConnectionStrings["RedisExchangeHosts"].ConnectionString;
private static readonly object Locker = new object();
private static ConnectionMultiplexer _instance;
private static readonly ConcurrentDictionary ConnectionCache = new ConcurrentDictionary();
///
/// Singleton mode
///
public static ConnectionMultiplexer Instance
{
get
{
if (_instance == null)
{
lock (Locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = GetManager();
}
}
}
return _instance;
}
}
///
/// get cache
///
///
///
public static ConnectionMultiplexer GetConnectionMultiplexer(string connectionString)
{
if (!ConnectionCache.ContainsKey(connectionString))
{
ConnectionCache[connectionString] = GetManager(connectionString);
}
return ConnectionCache[connectionString];
}
private static ConnectionMultiplexer GetManager(string connectionString = null)
{
connectionString = connectionString ?? RedisConnectionString;
var connect = ConnectionMultiplexer.Connect(connectionString);
//register some events
connect.ConnectionFailed += MuxerConnectionFailed;
connect.ConnectionRestored += MuxerConnectionRestored;
connect.ErrorMessage += MuxerErrorMessage;
connect.ConfigurationChanged += MuxerConfigurationChanged;
connect.HashSlotMoved += MuxerHashSlotMoved;
connect.InternalError += MuxerInternalError;
return connect;
}
#region events
///
/// When configuration changes
///
///
///
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
Console.WriteLine("Configuration changed: " + e.EndPoint);
}
///
/// When an error occurs
///
///
///
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
Console.WriteLine("ErrorMessage: " + e.Message);
}
///
/// Before re-establishing the connection error
///
///
///
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("ConnectionRestored: " + e.EndPoint);
}
///
/// Connection failed, if you reconnect successfully you will not receive this notification
///
///
///
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("Connection:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
}
///
/// Change the cluster
///
///
///
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
Console.WriteLine("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
}
///
/// Internal Error
///
///
///
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
Console.WriteLine("InternalError:Message" + e.Exception.Message);
}
#endregion events
}
}
2)使用
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommonTool.Redis
{
public class RedisHelper
{
private int DbNum { get; }
private readonly ConnectionMultiplexer _conn;
public string CustomKey;
#region Constructor
public RedisHelper(int dbNum = 0)
: this(dbNum, null)
{
}
public RedisHelper(int dbNum, string readWriteHosts)
{
DbNum = dbNum;
_conn =
string.IsNullOrWhiteSpace(readWriteHosts) ?
RedisConnectionHelp.Instance :
RedisConnectionHelp.GetConnectionMultiplexer(readWriteHosts);
}
#region Auxiliary methods
private string AddSysCustomKey(string oldKey)
{
var prefixKey = CustomKey ?? RedisConnectionHelp.SysCustomKey;
return prefixKey + oldKey;
}
private T Do(Func func)
{
var database = _conn.GetDatabase(DbNum);
return func(database);
}
private string ConvertJson(T value)
{
string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value);
return result;
}
private T ConvertObj(RedisValue value)
{
return JsonConvert.DeserializeObject(value);
}
private List ConvetList(RedisValue[] values)
{
List result = new List();
foreach (var item in values)
{
var model = ConvertObj(item);
result.Add(model);
}
return result;
}
private RedisKey[] ConvertRedisKeys(List redisKeys)
{
return redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray();
}
#endregion
#endregion Constuctor
#region String
#region Sync method
///
/// save single key value
///
/// Redis Key
/// save value
/// expiry time
///
public bool StringSet(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return Do(db => db.StringSet(key, value, expiry));
}
///
/// save multiple key value
///
/// key value pair
///
public bool StringSet(List> keyValues)
{
List> newkeyValues =
keyValues.Select(p => new KeyValuePair(AddSysCustomKey(p.Key), p.Value)).ToList();
return Do(db => db.StringSet(newkeyValues.ToArray()));
}
///
/// save an object
///
///
///
///
///
///
public bool StringSet(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string json = ConvertJson(obj);
return Do(db => db.StringSet(key, json, expiry));
}
///
/// get a single key
///
/// Redis Key
///
public string StringGet(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.StringGet(key));
}
///
/// get multiple keys
///
/// Redis Key collection
///
public RedisValue[] StringGet(List listKey)
{
List newKeys = listKey.Select(AddSysCustomKey).ToList();
return Do(db => db.StringGet(ConvertRedisKeys(newKeys)));
}
///
/// get an object by a key
///
///
///
///
public T StringGet(string key)
{
key = AddSysCustomKey(key);
return Do(db => ConvertObj(db.StringGet(key)));
}
///
/// Increase val for numbers
///
///
/// Can be negative
/// Increased value
public double StringIncrement(string key, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.StringIncrement(key, val));
}
///
/// Reduce val for numbers
///
///
/// can be negative
/// reduced value
public double StringDecrement(string key, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.StringDecrement(key, val));
}
#endregion
#region Asyn method
///
/// save single key value
///
/// Redis Key
/// save time
/// expiry time
///
public async Task StringSetAsync(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return await Do(db => db.StringSetAsync(key, value, expiry));
}
///
/// save multiple key value
///
/// key value pair
///
public async Task StringSetAsync(List> keyValues)
{
List> newkeyValues =
keyValues.Select(p => new KeyValuePair(AddSysCustomKey(p.Key), p.Value)).ToList();
return await Do(db => db.StringSetAsync(newkeyValues.ToArray()));
}
///
/// save an object
///
///
///
///
///
///
public async Task StringSetAsync(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string json = ConvertJson(obj);
return await Do(db => db.StringSetAsync(key, json, expiry));
}
///
/// get a single key
///
/// Redis Key
///
public async Task StringGetAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(db => db.StringGetAsync(key));
}
///
/// get multiple keys
///
/// Redis Key collection
///
public async Task StringGetAsync(List listKey)
{
List newKeys = listKey.Select(AddSysCustomKey).ToList();
return await Do(db => db.StringGetAsync(ConvertRedisKeys(newKeys)));
}
///
/// get an object from a key
///
///
///
///
public async Task StringGetAsync(string key)
{
key = AddSysCustomKey(key);
string result = await Do(db => db.StringGetAsync(key));
return ConvertObj(result);
}
///
/// increase val for numbers
///
///
/// can be negative
/// increased value
public async Task StringIncrementAsync(string key, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.StringIncrementAsync(key, val));
}
///
/// reduce val for numbers
///
///
/// can be negative
/// reduced value
public async Task StringDecrementAsync(string key, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.StringDecrementAsync(key, val));
}
#endregion
#endregion String
#region List
#region Sync method
///
/// Delete the corresponding value from list according to the key
///
///
///
public void ListRemove(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListRemove(key, ConvertJson(value)));
}
///
/// get the specific list according to the key
///
///
///
public List ListRange(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.ListRange(key);
return ConvetList(values);
});
}
///
/// into the queue
///
///
///
public void ListRightPush(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListRightPush(key, ConvertJson(value)));
}
///
/// out of the queue
///
///
///
///
public T ListRightPop(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListRightPop(key);
return ConvertObj(value);
});
}
///
/// into the stack
///
///
///
///
public void ListLeftPush(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListLeftPush(key, ConvertJson(value)));
}
///
/// out of stack
///
///
///
///
public T ListLeftPop(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListLeftPop(key);
return ConvertObj(value);
});
}
///
/// get the length of list according to the key
///
///
///
public long ListLength(string key)
{
key = AddSysCustomKey(key);
return Do(redis => redis.ListLength(key));
}
#endregion Sync method
#region Asyn method
///
/// remove the value with specific key in the list
///
///
///
public async Task ListRemoveAsync(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListRemoveAsync(key, ConvertJson(value)));
}
///
/// get a list by key
///
///
///
public async Task> ListRangeAsync(string key)
{
key = AddSysCustomKey(key);
var values = await Do(redis => redis.ListRangeAsync(key));
return ConvetList(values);
}
///
/// into the queue
///
///
///
public async Task ListRightPushAsync(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListRightPushAsync(key, ConvertJson(value)));
}
///
/// out of the queue
///
///
///
///
public async Task ListRightPopAsync(string key)
{
key = AddSysCustomKey(key);
var value = await Do(db => db.ListRightPopAsync(key));
return ConvertObj(value);
}
///
/// into the stack
///
///
///
///
public async Task ListLeftPushAsync(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListLeftPushAsync(key, ConvertJson(value)));
}
///
/// out of stack
///
///
///
///
public async Task ListLeftPopAsync(string key)
{
key = AddSysCustomKey(key);
var value = await Do(db => db.ListLeftPopAsync(key));
return ConvertObj(value);
}
///
/// get length of the list by key
///
///
///
public async Task ListLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.ListLengthAsync(key));
}
#endregion Asyn method
#endregion List
#region Hash
#region Sync method
///
/// if existed in the cache
///
///
///
///
public bool HashExists(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db => db.HashExists(key, dataKey));
}
///
/// save data into the hash table
///
///
///
///
///
///
public bool HashSet(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
return Do(db =>
{
string json = ConvertJson(t);
return db.HashSet(key, dataKey, json);
});
}
///
/// remove a single value in hash
///
///
///
///
public bool HashDelete(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db => db.HashDelete(key, dataKey));
}
///
/// remove multiple values in hash
///
///
///
///
public long HashDelete(string key, List dataKeys)
{
key = AddSysCustomKey(key);
//List dataKeys1 = new List() {"1","2"};
return Do(db => db.HashDelete(key, dataKeys.ToArray()));
}
///
/// get data from a hash table
///
///
///
///
///
public T HashGet(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db =>
{
string value = db.HashGet(key, dataKey);
return ConvertObj(value);
});
}
///
/// increase value for numbers
///
///
///
/// can be negative
/// increased value
public double HashIncrement(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.HashIncrement(key, dataKey, val));
}
///
/// reduce value for numbers
///
///
///
/// can be negative
/// reduced value
public double HashDecrement(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.HashDecrement(key, dataKey, val));
}
///
/// Get hashkey all Redis key
///
///
///
///
public List HashKeys(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
RedisValue[] values = db.HashKeys(key);
return ConvetList(values);
});
}
#endregion Sync method
#region Asyn method
///
/// if existed in the cache
///
///
///
///
public async Task HashExistsAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashExistsAsync(key, dataKey));
}
///
/// save data into the hash table
///
///
///
///
///
///
public async Task HashSetAsync(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
return await Do(db =>
{
string json = ConvertJson(t);
return db.HashSetAsync(key, dataKey, json);
});
}
///
/// remove a single value in hash
///
///
///
///
public async Task HashDeleteAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashDeleteAsync(key, dataKey));
}
///
/// remove multiple values in hash
///
///
///
///
public async Task HashDeleteAsync(string key, List dataKeys)
{
key = AddSysCustomKey(key);
//List dataKeys1 = new List() {"1","2"};
return await Do(db => db.HashDeleteAsync(key, dataKeys.ToArray()));
}
///
/// get data from a hash table
///
///
///
///
///
public async Task HashGeAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
string value = await Do(db => db.HashGetAsync(key, dataKey));
return ConvertObj(value);
}
///
/// increase value for numbers
///
///
///
/// can be negative
/// increased value
public async Task HashIncrementAsync(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashIncrementAsync(key, dataKey, val));
}
///
/// reduce value for numbers
///
///
///
/// can be negative
/// reduced value
public async Task HashDecrementAsync(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashDecrementAsync(key, dataKey, val));
}
///
/// Get hashkey all Redis key
///
///
///
///
public async Task> HashKeysAsync(string key)
{
key = AddSysCustomKey(key);
RedisValue[] values = await Do(db => db.HashKeysAsync(key));
return ConvetList(values);
}
#endregion Asyn method
#endregion Hash
#region SortedSet
#region Sync method
///
/// add
///
///
///
///
public bool SortedSetAdd(string key, T value, double score)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetAdd(key, ConvertJson(value), score));
}
///
/// delete
///
///
///
public bool SortedSetRemove(string key, T value)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetRemove(key, ConvertJson(value)));
}
///
/// getall
///
///
///
public List SortedSetRangeByRank(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.SortedSetRangeByRank(key);
return ConvetList(values);
});
}
///
/// get count in the colloection
///
///
///
public long SortedSetLength(string key)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetLength(key));
}
#endregion Sync method
#region Asyn method
///
/// add
///
///
///
///
public async Task SortedSetAddAsync(string key, T value, double score)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetAddAsync(key, ConvertJson(value), score));
}
///
/// delete
///
///
///
public async Task SortedSetRemoveAsync(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetRemoveAsync(key, ConvertJson(value)));
}
///
/// get all
///
///
///
public async Task> SortedSetRangeByRankAsync(string key)
{
key = AddSysCustomKey(key);
var values = await Do(redis => redis.SortedSetRangeByRankAsync(key));
return ConvetList(values);
}
///
/// get count in collection
///
///
///
public async Task SortedSetLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetLengthAsync(key));
}
#endregion Asyn method
#endregion SortedSet
#region key management
///
/// key management
///
/// redis key
/// if it is deleted
public bool KeyDelete(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyDelete(key));
}
///
/// delete mutiple keys
///
/// rediskey
/// deleted count
public long KeyDelete(List keys)
{
List newKeys = keys.Select(AddSysCustomKey).ToList();
return Do(db => db.KeyDelete(ConvertRedisKeys(newKeys)));
}
///
/// if the key is saved
///
/// redis key
///
public bool KeyExists(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyExists(key));
}
///
/// rename key
///
/// old redis key
/// new redis key
///
public bool KeyRename(string key, string newKey)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyRename(key, newKey));
}
///
/// set key expiry time
///
/// redis key
///
///
public bool KeyExpire(string key, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return Do(db => db.KeyExpire(key, expiry));
}
#endregion key
#region Publish Subscribe
///
/// Subscribe
///
///
///
public void Subscribe(string subChannel, Action handler = null)
{
ISubscriber sub = _conn.GetSubscriber();
sub.Subscribe(subChannel, (channel, message) =>
{
if (handler == null)
{
Console.WriteLine(subChannel + " subscription news:" + message);
}
else
{
handler(channel, message);
}
});
}
///
/// Publish
///
///
///
///
///
public long Publish(string channel, T msg)
{
ISubscriber sub = _conn.GetSubscriber();
return sub.Publish(channel, ConvertJson(msg));
}
///
/// cancle Subscribe
///
///
public void Unsubscribe(string channel)
{
ISubscriber sub = _conn.GetSubscriber();
sub.Unsubscribe(channel);
}
///
/// cancle Subscribe all
///
public void UnsubscribeAll()
{
ISubscriber sub = _conn.GetSubscriber();
sub.UnsubscribeAll();
}
#endregion
#region Others
public ITransaction CreateTransaction()
{
return GetDatabase().CreateTransaction();
}
public IDatabase GetDatabase()
{
return _conn.GetDatabase(DbNum);
}
public IServer GetServer(string hostAndPort)
{
return _conn.GetServer(hostAndPort);
}
///
/// set the prefix
///
///
public void SetSysCustomKey(string customKey)
{
CustomKey = customKey;
}
#endregion Others
}
}