|
|
using System;
|
|
|
using System.Collections.Generic;
|
|
|
using System.Linq;
|
|
|
using System.Text;
|
|
|
using System.Threading.Tasks;
|
|
|
using System.Net;
|
|
|
|
|
|
using StackExchange;
|
|
|
using StackExchange.Redis;
|
|
|
|
|
|
namespace RedisStuy
|
|
|
{
|
|
|
/// <summary>
|
|
|
/// 客户端操作
|
|
|
/// </summary>
|
|
|
public static class RedisHelper
|
|
|
{
|
|
|
/// <summary>
|
|
|
/// 获取 Redis连接
|
|
|
/// (此为共享和线程安全的,可以设计成单例模式)
|
|
|
/// </summary>
|
|
|
public static IConnectionMultiplexer GetConnectionMultiplexer()
|
|
|
{
|
|
|
ConfigurationOptions options = new ConfigurationOptions();
|
|
|
options.DefaultDatabase = 1;
|
|
|
options.AllowAdmin = true;
|
|
|
options.EndPoints.Add("127.0.0.1", 6379);
|
|
|
|
|
|
IConnectionMultiplexer connection = ConnectionMultiplexer.Connect(options);
|
|
|
|
|
|
return connection;
|
|
|
}
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
/// 获取 默认Reids服务器
|
|
|
/// </summary>
|
|
|
/// <returns></returns>
|
|
|
public static IServer GetDefaultRedisServer()
|
|
|
{
|
|
|
IConnectionMultiplexer connection = GetConnectionMultiplexer();
|
|
|
IServer redisServer = connection.GetServer(connection.GetEndPoints()[0]);
|
|
|
return redisServer;
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// 获取Redis连接上的所有Redis
|
|
|
/// </summary>
|
|
|
public static List<IServer> GetAllRedisServer()
|
|
|
{
|
|
|
List<IServer> redisServers = new List<IServer>();
|
|
|
IConnectionMultiplexer connection = GetConnectionMultiplexer();
|
|
|
EndPoint[] endPoints = connection.GetEndPoints();
|
|
|
foreach (EndPoint endPoint in endPoints)
|
|
|
{
|
|
|
redisServers.Add(connection.GetServer(endPoint));
|
|
|
}
|
|
|
|
|
|
return redisServers;
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// 获取 Redis数据库
|
|
|
/// </summary>
|
|
|
public static IDatabase GetRedisDatabase()
|
|
|
{
|
|
|
IConnectionMultiplexer connection = GetConnectionMultiplexer();
|
|
|
|
|
|
IDatabase redisDatabase = connection.GetDatabase();
|
|
|
|
|
|
return redisDatabase;
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// 获取 Redis数据库
|
|
|
/// </summary>
|
|
|
/// <param name="databaseIndex">
|
|
|
/// redis中数据库编号为0-15,超出则默认为0号数据库
|
|
|
/// </param>
|
|
|
public static IDatabase GetRedisDatabase(int databaseIndex)
|
|
|
{
|
|
|
//redis中数据库为0-15,超出则默认为0号数据库
|
|
|
if (databaseIndex<0 || databaseIndex>=16)
|
|
|
{
|
|
|
databaseIndex = 0;
|
|
|
}
|
|
|
|
|
|
IConnectionMultiplexer connection = GetConnectionMultiplexer();
|
|
|
|
|
|
IDatabase redisDatabase = connection.GetDatabase(databaseIndex);
|
|
|
|
|
|
return redisDatabase;
|
|
|
}
|
|
|
}
|
|
|
}
|