BotSharp/BotSharp.Core/AgentStorageInRedis.cs

108 lines
3 KiB
C#
Raw Normal View History

2018-10-01 01:27:57 +00:00
using BotSharp.Platform.Abstraction;
using BotSharp.Platform.Models;
using CSRedis;
using Microsoft.Extensions.Configuration;
2018-10-01 01:27:57 +00:00
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BotSharp.Core
{
public class AgentStorageInRedis<TAgent> : IAgentStorage<TAgent>
where TAgent : AgentBase
{
private static CSRedisClient csredis;
2018-10-01 17:15:17 +00:00
private static string prefix = String.Empty;
2018-10-01 01:27:57 +00:00
public AgentStorageInRedis()
{
if (csredis == null)
{
IConfiguration config = (IConfiguration)AppDomain.CurrentDomain.GetData("Configuration");
var db = config.GetSection("Database:Default").Value;
var dbConnStr = config.GetSection($"Database:ConnectionStrings:{db}").Value;
prefix = dbConnStr.Split(',').First(x => x.StartsWith("prefix=")).Split('=')[1];
csredis = new CSRedisClient(dbConnStr);
2018-10-01 01:27:57 +00:00
}
}
public TAgent FetchById(string agentId)
{
var key = agentId;
if (csredis.Exists(key))
{
return JsonConvert.DeserializeObject<TAgent>(csredis.Get(key));
}
else
{
return null;
}
}
public TAgent FetchByName(string agentName)
{
var agents = new List<TAgent>();
2018-10-01 17:15:17 +00:00
var keys = csredis.Keys($"{prefix}*");
2018-10-01 01:27:57 +00:00
foreach (string key in keys)
{
var data = csredis.Get(key.Substring(prefix.Length));
2018-10-01 01:27:57 +00:00
var agent = JsonConvert.DeserializeObject<TAgent>(data);
if(agent.Name == agentName)
{
return agent;
}
}
return default(TAgent);
}
public bool Persist(TAgent agent)
{
if (String.IsNullOrEmpty(agent.Id))
{
agent.Id = Guid.NewGuid().ToString();
}
2018-10-03 17:21:19 +00:00
var json = JsonConvert.SerializeObject(agent, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented,
});
csredis.Set(agent.Id, json);
2018-10-01 01:27:57 +00:00
return true;
}
public int PurgeAllAgents()
{
var keys = csredis.Keys($"{prefix}*");
csredis.Remove(keys.Select(x => x.Substring(prefix.Length)).ToArray());
return keys.Count();
}
2018-10-01 01:27:57 +00:00
public List<TAgent> Query()
{
var agents = new List<TAgent>();
var keys = csredis.Keys($"{prefix}*");
2018-10-01 01:27:57 +00:00
foreach (string key in keys)
{
var data = csredis.Get(key.Substring(prefix.Length));
2018-10-01 01:27:57 +00:00
var agent = JsonConvert.DeserializeObject<TAgent>(data);
agents.Add(agent);
}
return agents;
}
}
}