using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BPASmartClient.Compiler
{
public class FRedisClient
{
#region 单例模式
//private static FRedisClient instance = null;
//public static FRedisClient Instance()
//{
// if (instance == null) instance = new FRedisClient();
// return instance;
//}
#endregion
#region 变量
///
/// IP地址
///
public string redisconnection = "124.222.238.75:16000,password=123456";
///
/// redis 连接状态
///
public ConnectionMultiplexer _connection = null;
///
/// 数据存储位置
///
public IDatabase _database = null;
///
/// 通道建立连接
///
public ISubscriber subscibe = null;
#endregion
#region 外部访问
///
/// 委托出去
///
public Action LogMeaage = null;
#endregion
public void Connect()
{
_connection = ConnectionMultiplexer.Connect(ConfigurationOptions.Parse(redisconnection));
_database = _connection.GetDatabase(0);//默认使用db0
subscibe = _connection.GetSubscriber();
}
public void Connect(string connection)
{
_connection = ConnectionMultiplexer.Connect(ConfigurationOptions.Parse(connection));
if (connection.Contains("defaultDatabase="))
{
string[] str=connection.Split(',');
string stro = str.ToList().Find(s => s.Contains("defaultDatabase="));
int dbi = 0;
try
{
dbi=int.Parse(stro.Replace("defaultDatabase=",""));
}
catch (Exception ex)
{
throw;
}
_database = _connection.GetDatabase(dbi);//默认使用db0
}
else
{
_database = _connection.GetDatabase();//默认使用db0
}
subscibe = _connection.GetSubscriber();
}
///
/// 获取设备列表
///
///
public Dictionary GetKeys()
{
Dictionary keys = new Dictionary();
foreach (var endPoint in _connection.GetEndPoints())
{
//获取指定服务器
var server = _connection.GetServer(endPoint);
//在指定服务器上使用 keys 或者 scan 命令来遍历key
foreach (var key in server.Keys(0,"设备列表:*"))
{
//获取key对于的值
var val = _database.StringGet(key);
Console.WriteLine($"key: {key}, value: {val}");
keys[key] = val;
}
}
return keys;
}
///
/// 订阅通道消息
///
public void SubscribeChanne(string channelname)
{
if (subscibe == null) return;
subscibe.Subscribe(channelname,(channel,message) =>
{
MessageLog(channel,message);
});
}
///
/// 发布通道消息
///
public void PublishChanne(string channelname,string value)
{
if (subscibe == null) return;
subscibe.Publish(channelname,value);
}
///
/// 获取 key 值
///
public RedisValue RedisGet(string key,string hashField = "")
{
if (_database == null) return new RedisValue();
RedisValue result;
if (string.IsNullOrEmpty(hashField))
{
result = _database.StringGet(key);
}
else
{
result = _database.HashGet(key,hashField);
}
return result;
//MessageLog(key,result);
}
///
/// 设置 redis 的值
///
public bool RedisSet(string key,string hashField,string value)
{
bool result;
if (string.IsNullOrEmpty(hashField))
{
result = _database.StringSet(key,value);
}
else
{
result = _database.HashSet(key,hashField,value);
}
return result;
}
///
/// 消息打印
///
private void MessageLog(string key,string msg)
{
if (LogMeaage != null)
{
LogMeaage.Invoke(key,msg);
}
}
}
}