ClientService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Threading.Tasks;
  7. using ConsoleHttp;
  8. using ConsoleHttp.Model;
  9. using MqttMsgServer.Dao;
  10. using MqttMsgServer.HttpService.dto;
  11. using MqttMsgServer.Model;
  12. using MqttMsgServer.Redis;
  13. using MqttMsgServer.Service.Client.Dto;
  14. using MqttMsgServer.Tools;
  15. using MQTTnet.Protocol;
  16. using StackExchange.Redis;
  17. namespace MqttMsgServer.Service.Client
  18. {
  19. public interface IClientInfoService
  20. {
  21. ResponseResult AddOrUpdateClient(ClientDto input);
  22. ResponseResult RegisterClient(ClientDto input);
  23. ResponseResult UpdateClients(ClientDto input);
  24. void RefreshClientCache(ClientInfos input);
  25. ResponseResult ConnectServer(ConnectDto input);
  26. }
  27. public class ClientInfoService : IClientInfoService
  28. {
  29. //private readonly IRepository<string, ClientInfos> ClientsRepository;
  30. //private readonly IRepository<String,ReceiveMessageRecord> ReceiveMessageRecordRepository;
  31. protected RedisHelpers redisCache;
  32. public ClientInfoService()//IRepository<string, ClientInfos> clientsRepository, IRepository<string, ReceiveMessageRecord> receiveMessageRecordRepository
  33. {
  34. //ClientsRepository = clientsRepository;
  35. //ReceiveMessageRecordRepository = receiveMessageRecordRepository;
  36. this.redisCache = new RedisHelpers();
  37. }
  38. public ResponseResult ConnectServer(ConnectDto input)
  39. {
  40. ResponseResult result = new ResponseResult();
  41. if (string.IsNullOrEmpty(input.ClientName) || string.IsNullOrEmpty(input.ClientId) ||
  42. string.IsNullOrEmpty(input.Password))
  43. {
  44. return StringHelper.CheckError("请求字段为空!");
  45. }
  46. //var rs = RedisHelper.Instance.GetStringKey<ClientInfos>(CacheName.ClientCachePrefix + input.ClientId);
  47. var rs = redisCache.StringGet<ClientInfos>(CacheName.ClientCachePrefix + input.ClientId);
  48. if (rs == null)
  49. {
  50. string lcSql = $"select * from Clients where Id='{input.ClientId}';";
  51. DataTable dt = SqlDbHelper.ExecuteDataTable(lcSql);
  52. if (dt != null && dt.Rows.Count > 0)
  53. {
  54. rs= StringHelper.ToList<ClientInfos>(dt).FirstOrDefault();
  55. }
  56. }
  57. if (rs == null)
  58. {
  59. return StringHelper.CheckError("用户不存在!");
  60. }
  61. if (rs.ClientState == DefineConfig.ClientStateClosed)
  62. {
  63. return StringHelper.CheckError("账户已被锁定!");
  64. }
  65. var pwd = StringHelper.GenerateMD5(input.Password);
  66. if (pwd != rs.Password)
  67. {
  68. return StringHelper.CheckError("密码不正确!");
  69. }
  70. // RedisHelper.Instance.SetStringKey(CacheName.ClientCachePrefix + input.ClientId, rs, TimeSpan.FromHours(24));
  71. redisCache.StringSet(CacheName.ClientCachePrefix + input.ClientId, rs, TimeSpan.FromHours(24));
  72. return result;
  73. }
  74. public void RefreshClientCache(ClientInfos input)
  75. {
  76. //RedisHelper.Instance.SetStringKey(CacheName.ClientCachePrefix + input.Id, input, TimeSpan.FromHours(input.Hours));
  77. redisCache.StringSet(CacheName.ClientCachePrefix + input.Id, input, TimeSpan.FromHours(input.Hours));
  78. }
  79. public ResponseResult AddOrUpdateClient(ClientDto input)
  80. {
  81. ResponseResult result = new ResponseResult();
  82. if (string.IsNullOrEmpty(input.ClientName) || string.IsNullOrEmpty(input.Id) ||
  83. string.IsNullOrEmpty(input.Password))
  84. {
  85. return StringHelper.CheckError("编号,名称,密码请求字段为空!");
  86. }
  87. var check = GetClientInfo(input.Id);
  88. //typeof(SqlDbHelper).LogError("1.--查询对象");
  89. if (check == null)
  90. {
  91. ClientInfos c = new ClientInfos()
  92. {
  93. Id = input.Id,
  94. ClientName = input.ClientName,
  95. ClientState = input.ClientState,
  96. CreatorDate = DateTime.Now,
  97. CreatorUserId = 1,
  98. Password = StringHelper.GenerateMD5(input.Password),
  99. SystemDesc = input.SystemDesc,
  100. Hours = input.Hours
  101. };
  102. SqlDbHelper.ExecuteNonQuery(c.InsertSql());
  103. RefreshClientCache(c);
  104. }
  105. else
  106. {
  107. //typeof(SqlDbHelper).LogError("2.--查询到对象");
  108. ClientInfos c = new ClientInfos()
  109. {
  110. Id = input.Id,
  111. ClientName = string.IsNullOrEmpty(input.ClientName) ? check.ClientName : input.ClientName,
  112. ClientState = input.ClientState,
  113. Password = string.IsNullOrEmpty(input.Password) ? check.Password : StringHelper.GenerateMD5(input.Password),
  114. SystemDesc = string.IsNullOrEmpty(input.SystemDesc) ? check.SystemDesc : input.SystemDesc,
  115. Hours = input.Hours,
  116. CreatorDate = check.CreatorDate,
  117. CreatorUserId = check.CreatorUserId,
  118. };
  119. //typeof(SqlDbHelper).LogError("3.--创建到对象");
  120. SqlDbHelper.ExecuteNonQuery(c.UpdateSql());
  121. //typeof(SqlDbHelper).LogError("4.--更新数据库对象");
  122. RefreshClientCache(c);
  123. //typeof(SqlDbHelper).LogError("5.--更新缓存");
  124. }
  125. return result;
  126. }
  127. private ClientInfos GetClientInfo(string id)
  128. {
  129. ClientInfos check = null;
  130. string lcSql = $"select * from Clients where Id='{id}';";
  131. DataTable dt = SqlDbHelper.ExecuteDataTable(lcSql);
  132. if (dt != null && dt.Rows.Count > 0)
  133. {
  134. check = StringHelper.ToList<ClientInfos>(dt).FirstOrDefault();
  135. }
  136. return check;
  137. }
  138. public ResponseResult RegisterClient(ClientDto input)
  139. {
  140. ResponseResult result = new ResponseResult();
  141. if (string.IsNullOrEmpty(input.ClientName) || string.IsNullOrEmpty(input.Id) ||
  142. string.IsNullOrEmpty(input.Password))
  143. {
  144. return StringHelper.CheckError("编号,名称,密码请求字段为空!");
  145. }
  146. var check = GetClientInfo(input.Id);
  147. if (check != null)
  148. {
  149. return StringHelper.CheckError("clientId已经存在!");
  150. }
  151. ClientInfos c = new ClientInfos()
  152. {
  153. Id = input.Id,
  154. ClientName = input.ClientName,
  155. ClientState = input.ClientState,
  156. CreatorDate = DateTime.Now,
  157. CreatorUserId = 1,
  158. Password = StringHelper.GenerateMD5(input.Password),
  159. SystemDesc = input.SystemDesc,
  160. Hours = input.Hours
  161. };
  162. SqlDbHelper.ExecuteNonQuery(c.InsertSql());
  163. RefreshClientCache(c);
  164. return result;
  165. }
  166. public ResponseResult UpdateClients(ClientDto input)
  167. {
  168. ResponseResult result = new ResponseResult();
  169. if ( string.IsNullOrEmpty(input.Id) )
  170. {
  171. return StringHelper.CheckError("编码字段为空!");
  172. }
  173. var check = GetClientInfo(input.Id);
  174. if (check == null)
  175. {
  176. return StringHelper.CheckError("clientId不存在!");
  177. }
  178. ClientInfos c = new ClientInfos()
  179. {
  180. Id = input.Id,
  181. ClientName = string.IsNullOrEmpty(input.ClientName)?check.ClientName:input.ClientName,
  182. ClientState = input.ClientState,
  183. Password = string.IsNullOrEmpty(input.Password)?check.Password:StringHelper.GenerateMD5(input.Password),
  184. SystemDesc = string.IsNullOrEmpty(input.SystemDesc)?check.SystemDesc:input.SystemDesc,
  185. Hours = input.Hours,
  186. CreatorDate = check.CreatorDate,
  187. CreatorUserId = check.CreatorUserId,
  188. };
  189. SqlDbHelper.ExecuteNonQuery(c.UpdateSql());
  190. RefreshClientCache(c);
  191. return result;
  192. }
  193. public void WriteCache(string clientId, string topic, string msg)
  194. {
  195. var entity = new ReceiveMessageRecord()
  196. {
  197. Id = Guid.NewGuid().ToString("N"),
  198. ClientId = clientId,
  199. Topic = topic,
  200. Payload = msg,
  201. QualityOfServiceLevel= MqttQualityOfServiceLevel.AtLeastOnce,
  202. CreatorDate = DateTime.Now,
  203. CreatorUserId = 1
  204. };
  205. WriteData(entity);
  206. }
  207. public void WriteData(ReceiveMessageRecord pReceiveMessageRecord)
  208. {
  209. WriteCache(pReceiveMessageRecord);
  210. Action ac = () => { WriteRecordToDb(pReceiveMessageRecord); };
  211. ac.Invoke();
  212. }
  213. public void WriteCache(ReceiveMessageRecord pReceiveMessageRecord)
  214. {
  215. //List<ReceiveMessageRecord> rs = redisCache.StringGet<List<ReceiveMessageRecord>>(CacheName.TopicMsgCachePrefix + pReceiveMessageRecord.Topic) ?? new List<ReceiveMessageRecord>();
  216. //if (rs.Any())
  217. //{
  218. // DateTime currentDay = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
  219. // rs = rs.Where(i => i.CreatorDate > currentDay).Take(100).ToList();
  220. //}
  221. //rs.Add(pReceiveMessageRecord);
  222. //redisCache.StringSet(CacheName.TopicMsgCachePrefix + pReceiveMessageRecord.Topic, rs, TimeSpan.FromDays(1));
  223. int retainMinute = AppSetting.GetInt("redisMsgTTL");
  224. redisCache.ListRightPush(CacheName.TopicMsgCachePrefix + pReceiveMessageRecord.Topic, pReceiveMessageRecord, TimeSpan.FromMinutes(retainMinute));
  225. //List<ReceiveMessageRecord> rs2 = redisCache.StringGet<List<ReceiveMessageRecord>>(CacheName.ClientMsgCachePrefix + pReceiveMessageRecord.ClientId) ?? new List<ReceiveMessageRecord>();
  226. //if (rs2.Any())
  227. //{
  228. // DateTime currentDay = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
  229. // rs2 = rs2.Where(i => i.CreatorDate > currentDay).Take(100).ToList();
  230. //}
  231. //rs2.Add(pReceiveMessageRecord);
  232. //redisCache.StringSet(CacheName.ClientMsgCachePrefix + pReceiveMessageRecord.ClientId, rs2, TimeSpan.FromDays(1));
  233. redisCache.ListRightPush(CacheName.ClientMsgCachePrefix + pReceiveMessageRecord.ClientId, pReceiveMessageRecord, TimeSpan.FromMinutes(retainMinute));
  234. }
  235. public void WriteRecordToDb(ReceiveMessageRecord pReceiveMessageRecord)
  236. {
  237. try
  238. {
  239. SqlDbHelper.ExecuteNonQuery(pReceiveMessageRecord.InsertSql());
  240. }
  241. catch (Exception e)
  242. {
  243. Console.WriteLine(e);
  244. }
  245. }
  246. }
  247. }