Repository navigation
Expand file tree
/
Copy pathAgentStorageInRedis.cs
More file actions
108 lines (89 loc) · 3.05 KB
/
Copy pathAgentStorageInRedis.cs
File metadata and controls
108 lines (89 loc) · 3.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using BotSharp.Platform.Abstraction;
using BotSharp.Platform.Models;
using CSRedis;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BotSharp.Core
{
public class AgentStorageInRedis<TAgent> : IAgentStorage<TAgent>
where TAgent : AgentBase
{
private static CSRedisClient csredis;
private static string prefix = String.Empty;
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);
}
}
public async Task<TAgent> FetchById(string agentId)
{
var key = agentId;
if (csredis.Exists(key))
{
return JsonConvert.DeserializeObject<TAgent>(csredis.Get(key));
}
else
{
return null;
}
}
public async Task<TAgent> FetchByName(string agentName)
{
var agents = new List<TAgent>();
var keys = csredis.Keys($"{prefix}*");
foreach (string key in keys)
{
var data = csredis.Get(key.Substring(prefix.Length));
var agent = JsonConvert.DeserializeObject<TAgent>(data);
if(agent.Name == agentName)
{
return agent;
}
}
return default(TAgent);
}
public async Task<bool> Persist(TAgent agent)
{
if (String.IsNullOrEmpty(agent.Id))
{
agent.Id = Guid.NewGuid().ToString();
}
var json = JsonConvert.SerializeObject(agent, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented,
});
csredis.Set(agent.Id, json);
return true;
}
public async Task<int> PurgeAllAgents()
{
var keys = csredis.Keys($"{prefix}*");
csredis.Remove(keys.Select(x => x.Substring(prefix.Length)).ToArray());
return keys.Count();
}
public async Task<List<TAgent>> Query()
{
var agents = new List<TAgent>();
var keys = csredis.Keys($"{prefix}*");
foreach (string key in keys)
{
var data = csredis.Get(key.Substring(prefix.Length));
var agent = JsonConvert.DeserializeObject<TAgent>(data);
agents.Add(agent);
}
return agents;
}
}
}