[转]Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager

转自:http://www.cnblogs.com/oppoic/p/6165581.html

Redis缓存服务器是一款key/value数据库,读110000次/s,写81000次/s,因为是内存操作所以速度飞快,常见用法有存用户令牌、短信验证码等

官网显示Redis本身并没有Windows版本的,微软官方开发了基于Windows的Redis服务器:MSOpenTech/redis

一、Redis服务端

首先下载Redis服务器,点击前往下载.msi版本,双击安装Redis服务端就有了,并以服务的形式随系统一起启动:

[转]Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager

安装好Redis服务器之后第一件事就是设置密码,进入安装目录:C:\Program Files\Redis - 找到配置文件:redis.windows-service.conf - 找到:# requirepass foobared - 回车换行加上:requirepass 这里写自己的新密码(顶行写,前面不要留空格) - 到服务里重启Redis服务,或者重启电脑

不设置密码的坏处,看看携程这哥们的遭遇就知道了:记一次Redis被攻击的事件

二、Redis客户端(命令行和可视化工具RDM)

命令行方式演示:启动Redis客户端、读写Redis服务器

[转]Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager

上图命令解释:

cd C:\Program Files\Redis:cd命令进入Redis安装目录,相当于Windows系统里双击进入Redis的安装目录

redis-cli.exe:打开redis-cli客户端程序,相当于Windows系统里双击运行一个exe程序(安装了上面的Redis服务端程序,需要一个客户端程序连接这个服务端。连接本机redis服务器直接敲此命令,连接远程的需要加ip和端口,例:redis-cli.exe -h 111.11.11.111 -p 6379)

keys *:查看所有键值对(如果Redis服务器设置了密码,这条命令会报错,需要先输入密码,执行此命令:auth 你的密码)

set blog oppoic.cnblogs.com:设置一个键值对,键是:blog,值是:oppoic.cnblogs.com(按目录存储:set 目录名:键 值)

get blog:获取键为blog对应的值

keys *:查看所有键值对

其他常用命令:

config get dir:获取redis安装目录

ping:返回PONG表示redis服务器正常

redis-cli.exe:进入第一个数据库(默认),redis一共0到15共16个库,进入第三个库 redis-cli -n 2(已经进去了,select 0~15 随意切换)

quit:退出redis程序

exit:退出dos窗口

flushdb:删除当前选择数据库中的所有key

flushall:删除所有数据库中的数据库

更多命令:https://redis.io/commands

至此,一个运行在本机的Redis缓存服务器已经搭建完成,并且可以读写了。但是命令行显然对小白用户不友好,可视化工具登场:Redis Desktop Manager

[转]Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager

左侧树显示已经有一个连接了,点击底部的Connect to Redis Server再添加一个连接:

Name:连接名称,随便起

Host:主机地址,本机就是127.0.0.1,远程的输入对应IP

Port:端口,Redis服务器默认端口6379

Auth:密码,设置了就输,没设置留空

连上Redis服务器就可以看到,默认16个库(配置文件可改),索引从0开始。常见用法是一个项目一个库,项目下不同功能模块分不同目录存在这个库下。

有了可视化工具之后的操作就不用说了,双击,右键新建、删除。。。会用Windows系统的都会用这个工具。相比于命令行,Redis Desktop Manager这个可视化工具更友好,调试远程服务器上的数据也更方便,指哪打哪。

注:本机可以这样,连接远程服务器需要到服务器上的Redis安装目录下,找到redis.windows-service.conf文件,找到bind 127.0.0.1 前面加"#"注释掉,然后到服务里右键重启redis服务

三、C#操作Redis服务器

以上都是命令行和可视化工具操作Redis服务器,C#程序操作Redis需要借助StackExchange.Redis,为了统一调用,封装了一个RedisHelper帮助类:

2017.02.08:RedisHelper.cs代码有修改,请下载文章结尾提供的源码

using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Reflection;
using System.Text;
using System.Linq; namespace redis_Demo
{
/// <summary>
/// Redis 帮助类
/// </summary>
public static class RedisHelper
{
private static string _conn = ConfigurationManager.AppSettings["redis_connection_string"] ?? "127.0.0.1:6379";
private static string _pwd = ConfigurationManager.AppSettings["redis_connection_pwd"] ?? "";
private static int _store_db = string.IsNullOrEmpty(ConfigurationManager.AppSettings["redis_store_db"]) ? - : Convert.ToInt32(ConfigurationManager.AppSettings["redis_store_db"]); static ConnectionMultiplexer _redis;
static readonly object _locker = new object(); #region 单例模式
public static ConnectionMultiplexer Manager
{
get
{
if (_redis == null)
{
lock (_locker)
{
if (_redis != null) return _redis;
_redis = GetManager();
return _redis;
}
}
return _redis;
}
} private static ConnectionMultiplexer GetManager(string connectionString = null)
{
if (string.IsNullOrEmpty(connectionString))
{
connectionString = _conn;
}
var options = ConfigurationOptions.Parse(connectionString);
options.Password = _pwd;
return ConnectionMultiplexer.Connect(options);
}
#endregion #region 辅助方法
/// <summary>
/// 获取要操作的库
/// </summary>
/// <param name="db">库,0和-1都是第一个库,1是第二个库...</param>
/// <returns></returns>
private static int GetOperationDB(int db)
{
if (db == -)
{
return _store_db;
}
else
{
return db;
}
} private static string ConvertJson<T>(T value)
{
string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value);
return result;
} private static T ConvertObj<T>(RedisValue value)
{
if (string.IsNullOrEmpty(value))
{
return default(T);
}
else
{
return JsonConvert.DeserializeObject<T>(value);
}
} private static List<T> ConvetList<T>(RedisValue[] values)
{
List<T> result = new List<T>();
foreach (var item in values)
{
var model = ConvertObj<T>(item);
if (model != null)
result.Add(model);
}
return result;
} private static RedisKey[] ConvertRedisKeys(List<string> redisKeys, string prefix)
{
if (string.IsNullOrEmpty(prefix))
{
return redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray();
}
else
{
return redisKeys.Select(redisKey => (RedisKey)(prefix + ":" + redisKey)).ToArray();
}
} /// <summary>
/// 获得枚举的Description
/// </summary>
/// <param name="value">枚举值</param>
/// <param name="nameInstead">当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param>
/// <returns>枚举的Description</returns>
private static string GetDescription(this Enum value, Boolean nameInstead = true)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name == null)
{
return null;
} FieldInfo field = type.GetField(name);
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attribute == null && nameInstead == true)
{
return name;
}
return attribute == null ? null : attribute.Description;
}
#endregion #region 通用(key)
/// <summary>
/// 是否存在
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="db">库,默认读取配置文件</param>
public static bool KeyExists(CacheFolderEnum folder, string key, int db = -)
{
try
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).KeyExists(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 设置过期时间
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="min">过期时间,单位:分钟</param>
/// <param name="db">库,默认读取配置文件</param>
public static bool KeyExpire(CacheFolderEnum folder, string key, int min = , int db = -)
{
try
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).KeyExpire(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, DateTime.Now.AddMinutes(min));
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 修改键
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="newKey">新键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool KeyRename(CacheFolderEnum folder, string key, string newKey, int db = -)
{
try
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).KeyRename(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, string.IsNullOrEmpty(fd) ? newKey : fd + ":" + newKey);
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 删除
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool KeyDelete(CacheFolderEnum folder, string key, int db = -)
{
try
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).KeyDelete(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 批量删除
/// </summary>
/// <param name="folder">目录</param>
/// <param name="keys">键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long KeyDelete(CacheFolderEnum folder, List<string> keys, int db = -)
{
try
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).KeyDelete(ConvertRedisKeys(keys, fd));
}
catch (Exception)
{
return ;
}
}
#endregion #region String
/// <summary>
/// 添加单个
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="expireMinutes">过期时间,单位:分钟</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool StringSet(CacheFolderEnum folder, string key, string value, int expireMinutes = , int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).StringSet(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, value, TimeSpan.FromMinutes(expireMinutes));
} /// <summary>
/// 批量添加
/// </summary>
/// <param name="folder">目录</param>
/// <param name="keysStr">键</param>
/// <param name="valuesStr">值</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool StringSet(CacheFolderEnum folder, string[] keysStr, string[] valuesStr, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
var count = keysStr.Length;
var keyValuePair = new KeyValuePair<RedisKey, RedisValue>[count];
for (int i = ; i < count; i++)
{
keyValuePair[i] = new KeyValuePair<RedisKey, RedisValue>(string.IsNullOrEmpty(fd) ? keysStr[i] : fd + ":" + keysStr[i], valuesStr[i]);
}
return Manager.GetDatabase(db).StringSet(keyValuePair);
} /// <summary>
/// 添加对象
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="obj">值</param>
/// <param name="expireMinutes">过期时间,单位:分钟</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool StringSet<T>(CacheFolderEnum folder, string key, T obj, int expireMinutes = , int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
string json = ConvertJson(obj);
return Manager.GetDatabase(db).StringSet(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, json, TimeSpan.FromMinutes(expireMinutes));
} /// <summary>
/// 获取单个
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static string StringGet(CacheFolderEnum folder, string key, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).StringGet(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
} /// <summary>
/// 获取多个
/// </summary>
/// <param name="folder">目录</param>
/// <param name="keys">键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static RedisValue[] StringGet(CacheFolderEnum folder, List<string> keys, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).StringGet(ConvertRedisKeys(keys, fd));
} /// <summary>
/// 获取对象
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static T StringGet<T>(CacheFolderEnum folder, string key, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
string value = Manager.GetDatabase(db).StringGet(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
return ConvertObj<T>(value);
}
#endregion #region List
/// <summary>
/// 获取
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="start">索引开始</param>
/// <param name="stop">索引结束</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static List<T> ListRange<T>(CacheFolderEnum folder, string key, long start = , long stop = -, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
var value = Manager.GetDatabase(db).ListRange(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, start, stop);
return ConvetList<T>(value);
} /// <summary>
/// 获取指定
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="index">索引</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static T ListGetByIndex<T>(CacheFolderEnum folder, string key, long index, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
var value = Manager.GetDatabase(db).ListGetByIndex(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, index);
return ConvertObj<T>(value);
} /// <summary>
/// 替换指定
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="index">索引</param>
/// <param name="value">值</param>
/// <param name="db">库,默认读取配置文件</param>
public static void ListSetByIndex<T>(CacheFolderEnum folder, string key, long index, T value, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
Manager.GetDatabase(db).ListSetByIndex(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, index, ConvertJson(value));
} /// <summary>
/// 删除指定
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="count">count > 0: Remove elements equal to value moving from head to tail.count 小于 0: Remove elements equal to value moving from tail to head.count = 0: Remove all elements equal to value.</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long ListRemove<T>(CacheFolderEnum folder, string key, T value, long count = , int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).ListRemove(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, ConvertJson(value), count);
} /// <summary>
/// 指定位置之后插入
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="pivot">位置</param>
/// <param name="value">值</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long ListInsertAfter<T>(CacheFolderEnum folder, string key, T pivot, T value, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).ListInsertAfter(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, ConvertJson(pivot), ConvertJson(value));
} /// <summary>
/// 指定位置之前插入
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="pivot">位置</param>
/// <param name="value">值</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long ListInsertBefore<T>(CacheFolderEnum folder, string key, T pivot, T value, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).ListInsertBefore(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, ConvertJson(pivot), ConvertJson(value));
} /// <summary>
/// 入栈(后插入的在List前面)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="db">库,默认读取配置文件</param>
public static long ListLeftPush<T>(CacheFolderEnum folder, string key, T value, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).ListLeftPush(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, ConvertJson(value));
} /// <summary>
/// 批量入栈(后插入的在List前面)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="values">值</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long ListLeftPush<T>(CacheFolderEnum folder, string key, List<T> values, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
var redisValues = values.Select(m => (RedisValue)ConvertJson(m)).ToArray();
return Manager.GetDatabase(db).ListLeftPush(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, redisValues);
} /// <summary>
/// 出栈(删除最前面的一个元素并返回)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static T ListLeftPop<T>(CacheFolderEnum folder, string key, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
var value = Manager.GetDatabase(db).ListLeftPop(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
return ConvertObj<T>(value);
} /// <summary>
/// 入队(后插入的在List后面)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="db">库,默认读取配置文件</param>
public static long ListRightPush<T>(CacheFolderEnum folder, string key, T value, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).ListRightPush(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, ConvertJson(value));
} /// <summary>
/// 批量入队(后插入的在List后面)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="values">值</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long ListRightPush<T>(CacheFolderEnum folder, string key, List<T> values, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
var redisValues = values.Select(m => (RedisValue)ConvertJson(m)).ToArray();
return Manager.GetDatabase(db).ListRightPush(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, redisValues);
} /// <summary>
/// 出队(删除最后面的一个元素并返回)
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static T ListRightPop<T>(CacheFolderEnum folder, string key, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
var value = Manager.GetDatabase(db).ListRightPop(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
return ConvertObj<T>(value);
} /// <summary>
/// 获取个数
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long ListLength(CacheFolderEnum folder, string key, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).ListLength(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
}
#endregion #region Hash
/// <summary>
/// 添加
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="dataKey">元素的键</param>
/// <param name="t">实体</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool HashSet<T>(CacheFolderEnum folder, string key, string dataKey, T t, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).HashSet(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, dataKey, ConvertJson(t));
} /// <summary>
/// 获取特定
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="dataKey">元素的键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static T HashGet<T>(CacheFolderEnum folder, string key, string dataKey, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
string value = Manager.GetDatabase(db).HashGet(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, dataKey);
return ConvertObj<T>(value);
} /// <summary>
/// 批量获取
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="dataKeys">元素的键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static List<T> HashGet<T>(CacheFolderEnum folder, string key, RedisValue[] dataKeys, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
var value = Manager.GetDatabase(db).HashGet(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, dataKeys);
return ConvetList<T>(value);
} /// <summary>
/// 获取所有
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static HashEntry[] HashGetAll<T>(CacheFolderEnum folder, string key, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).HashGetAll(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
} /// <summary>
/// 删除特定
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="dataKey">元素的键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool HashDelete(CacheFolderEnum folder, string key, string dataKey, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).HashDelete(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, dataKey);
} /// <summary>
/// 批量删除
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="dataKeys">元素的键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long HashDelete(CacheFolderEnum folder, string key, List<RedisValue> dataKeys, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).HashDelete(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, dataKeys.ToArray());
} /// <summary>
/// 是否存在
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="dataKey">元素的键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool HashExists(CacheFolderEnum folder, string key, string dataKey, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).HashExists(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, dataKey);
}
#endregion #region Zset
/// <summary>
/// 添加
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="score">排序列</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool SortedSetAdd<T>(CacheFolderEnum folder, string key, T value, double score, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).SortedSetAdd(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, ConvertJson<T>(value), score);
} /// <summary>
/// 获取
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="start">索引开始</param>
/// <param name="stop">索引结束</param>
/// <param name="order">排序方式</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static List<T> SortedSetRangeByRank<T>(CacheFolderEnum folder, string key, long start = , long stop = -, Order order = Order.Ascending, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
var values = Manager.GetDatabase(db).SortedSetRangeByRank(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, start, stop, order);
return ConvetList<T>(values);
} /// <summary>
/// 删除
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static bool SortedSetRemove<T>(CacheFolderEnum folder, string key, T value, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).SortedSetRemove(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, ConvertJson<T>(value));
} /// <summary>
/// 批量删除(根据对象)
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="values">对象</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long SortedSetRemove<T>(CacheFolderEnum folder, string key, List<T> values, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
var redisValues = values.Select(m => (RedisValue)ConvertJson(m)).ToArray();
return Manager.GetDatabase(db).SortedSetRemove(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, redisValues);
} /// <summary>
/// 批量删除(根据score删除)
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="start">开始</param>
/// <param name="stop">结束</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long SortedSetRemoveRangeByScore(CacheFolderEnum folder, string key, int start, int stop, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).SortedSetRemoveRangeByScore(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, start, stop);
} /// <summary>
/// 获取总数
/// </summary>
/// <param name="folder">目录</param>
/// <param name="key">键</param>
/// <param name="db">库,默认读取配置文件</param>
/// <returns></returns>
public static long SortedSetLength(CacheFolderEnum folder, string key, int db = -)
{
db = GetOperationDB(db);
string fd = GetDescription(folder);
return Manager.GetDatabase(db).SortedSetLength(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
}
#endregion }
}

String

RedisHelper.StringSet(CacheFolderEnum.Folder1, "string", "hello world", 60);

效果:

[转]Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager

List

RedisHelper.ListRightPush(CacheFolderEnum.Folder2, "list", student1);
RedisHelper.ListRightPush(CacheFolderEnum.Folder2, "list", student2);
RedisHelper.ListRightPush(CacheFolderEnum.Folder2, "list", student3);

效果:

[转]Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager

Hash

RedisHelper.HashSet<Student>(CacheFolderEnum.Folder3, "hash", "h1", student1);
RedisHelper.HashSet<Student>(CacheFolderEnum.Folder3, "hash", "h2", student2);

效果:

[转]Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager

SortedSet

RedisHelper.SortedSetAdd<Student>(CacheFolderEnum.Folder3, "zsort", student1, 111);
RedisHelper.SortedSetAdd<Student>(CacheFolderEnum.Folder3, "zsort", student2, 99);
RedisHelper.SortedSetAdd<Student>(CacheFolderEnum.Folder3, "zsort", student3, 100);

效果:(有序集合。不管插入顺序,始终按照score排好顺序)

[转]Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager

注:

1.把要操作的目录写到枚举里,方便程序统一调用,不容易出错。如果多个目录嵌套就在Description上写[Description("一级目录:二级目录:三级目录")]

2.配置文件里的redis_store_db节点表示默认存在哪个库里,帮助类的每个方法也单独接收db参数,方便个性化存储到特定库

四、其他

源码:点击下载  环境是VS 2013,如果跑不起来自行把cs里的代码拷出来编译运行

爬虫可耻,本文原始链接:http://www.cnblogs.com/oppoic/p/6165581.html

参考资料:

Redis 命令 | 菜鸟教程

.NET中使用Redis

基础拾遗------redis详解

怎样在Redis通过StackExchange.Redis 存储集合类型List

StackExchange.Redis通用封装类分享

做个简单的Redis监控(源码分享)

------------------------------------------补充:更新后的RedisHelper用法有点变化--------------------------------------------

 private void button3_Click(object sender, EventArgs e)
{
RedisHelper.StringSet( "string", "hello world", 1);
RedisHelper.StringSet("string", "hello world1",1,RedisFolderEnum.Folder1,RedisDBEnum.Two); List<Student> list = new List<Student>();
list.Add(new Student() { NO = 001,Name = "001Name", Age=21});
list.Add(new Student() { NO = 002, Name = "002Name", Age = 21 });
list.Add(new Student() { NO = 003, Name = "003Name", Age = 21 }); RedisHelper.ListRightPush<Student>("student", list, RedisFolderEnum.Root, RedisDBEnum.Three); ///获取第2个
var stu=RedisHelper.ListGetByIndex<Student>("student", 1,RedisFolderEnum.Root,RedisDBEnum.Three); var ret=RedisHelper.HashSet<Student>("studentHash", stu.Name, stu, RedisFolderEnum.Root, RedisDBEnum.Four); stu = RedisHelper.ListGetByIndex<Student>("student", 2, RedisFolderEnum.Root, RedisDBEnum.Three);
var ret1 = RedisHelper.HashSet<Student>("studentHash", stu.Name, stu, RedisFolderEnum.Root, RedisDBEnum.Four);
var tmpS=RedisHelper.HashGet<Student>("studentHash", new StackExchange.Redis.RedisValue[] { "002Name","003Name" }, RedisFolderEnum.Root, RedisDBEnum.Four); var temList=RedisHelper.ListRange<Student>("student", 0, -1, RedisFolderEnum.Root, RedisDBEnum.Three);
}
}
public class Student
{
public int NO { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}

  

From:http://www.cnblogs.com/xuejianxiyang/p/7084005.html

上一篇:StackExchange.Redis客户端读写主从配置,以及哨兵配置。


下一篇:Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager