RedisController.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using Cksoft.Unity;
  2. using DllEapCommon.Redis;
  3. using DllEapEntity;
  4. using LazyCache;
  5. using Microsoft.AspNetCore.Mvc;
  6. using StackExchange.Redis;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Data;
  10. using System.Linq;
  11. using System.Threading.Tasks;
  12. namespace WebMainFrameForEap.Controllers
  13. {
  14. [ApiController]
  15. [Route("eap/api/redis/[action]")]
  16. public class RedisController : Controller
  17. {
  18. private readonly IDatabase _db;
  19. private readonly IAppCache _appCache;
  20. public RedisController(RedisHelper redisHelper, IAppCache appCache)
  21. {
  22. _db = redisHelper.GetDatabase();
  23. _appCache = appCache;
  24. }
  25. public async Task<string> Get()
  26. {
  27. var value = await _db.StringGetAsync(new RedisKey("name"));
  28. _appCache.Add<Machine>("testmac", new Machine { ID = 2, FCode = "AA00001" });
  29. var mac = await _appCache.GetAsync<Machine>("testmac");
  30. return mac.ToJson();
  31. }
  32. public async Task<string> Set(string value)
  33. {
  34. await _db.StringSetAsync(new RedisKey("name"), new RedisValue(value));
  35. return "ok";
  36. }
  37. public async Task<string> SetTableRows()
  38. {
  39. var dt = new DataTable();
  40. dt.Columns.Add("Id");
  41. dt.Columns.Add("FCode");
  42. dt.Columns.Add("FName");
  43. dt.Columns.Add("SupplierCode");
  44. for (int i = 0; i < 2; i++)
  45. {
  46. var row = dt.NewRow();
  47. row["Id"] = i + 1;
  48. row["FCode"] = "FCode" + i + 1;
  49. row["FName"] = "FName" + i + 1;
  50. row["SupplierCode"] = "SupplierCode" + i + 1;
  51. dt.Rows.Add(row);
  52. }
  53. foreach (DataRow row in dt.Rows)
  54. {
  55. var hashEntries = new List<HashEntry>();
  56. foreach (DataColumn col in dt.Columns)
  57. {
  58. var tmp = new HashEntry(col.ColumnName, row[col.ColumnName].ToString());
  59. hashEntries.Add(tmp);
  60. }
  61. await _db.HashSetAsync("MacModel" + row["Id"].ToString(), hashEntries.ToArray());
  62. }
  63. return "ok";
  64. }
  65. public async Task<string> GetHashRow()
  66. {
  67. var vals = await _db.HashGetAllAsync("MacModel1");
  68. var str = string.Empty;
  69. foreach (var item in vals)
  70. {
  71. str += item.Name + "=" + item.Value + ",";
  72. }
  73. return str;
  74. }
  75. }
  76. }