RedisDemo.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using Apq.Cfg.Redis;
  2. namespace Apq.Cfg.Samples.Demos;
  3. /// <summary>
  4. /// 示例 9: Redis 配置源
  5. /// 注意:需要运行 Redis 服务才能执行此示例
  6. /// </summary>
  7. public static class RedisDemo
  8. {
  9. public static async Task RunAsync(string baseDir)
  10. {
  11. Console.WriteLine("═══════════════════════════════════════════════════════════════");
  12. Console.WriteLine("示例 9: Redis 配置源");
  13. Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
  14. Console.WriteLine("注意:此示例需要运行 Redis 服务 (localhost:6379)\n");
  15. try
  16. {
  17. // 构建 Redis 配置源
  18. Console.WriteLine("9.1 连接 Redis 配置源:");
  19. var cfg = new CfgBuilder()
  20. .AddRedis(options =>
  21. {
  22. options.ConnectionString = "localhost:6379";
  23. options.KeyPrefix = "apq:samples:";
  24. options.Database = 0;
  25. options.ConnectTimeoutMs = 3000;
  26. }, level: 0, isPrimaryWriter: true)
  27. .Build();
  28. Console.WriteLine(" 已连接到 Redis");
  29. // 写入配置
  30. Console.WriteLine("\n9.2 写入配置到 Redis:");
  31. cfg.Set("App:Name", "RedisApp");
  32. cfg.Set("App:Version", "1.0.0");
  33. cfg.Set("Database:Host", "db.example.com");
  34. cfg.Set("Database:Port", "5432");
  35. await cfg.SaveAsync();
  36. Console.WriteLine(" 已写入 4 个配置项");
  37. // 读取配置
  38. Console.WriteLine("\n9.3 从 Redis 读取配置:");
  39. Console.WriteLine($" App:Name = {cfg.Get("App:Name")}");
  40. Console.WriteLine($" App:Version = {cfg.Get("App:Version")}");
  41. Console.WriteLine($" Database:Host = {cfg.Get("Database:Host")}");
  42. Console.WriteLine($" Database:Port = {cfg.Get<int>("Database:Port")}");
  43. // 检查配置是否存在
  44. Console.WriteLine("\n9.4 检查配置是否存在:");
  45. Console.WriteLine($" Exists(App:Name) = {cfg.Exists("App:Name")}");
  46. Console.WriteLine($" Exists(NotExist) = {cfg.Exists("NotExist")}");
  47. // 删除配置
  48. Console.WriteLine("\n9.5 删除配置:");
  49. cfg.Remove("App:Name");
  50. cfg.Remove("App:Version");
  51. cfg.Remove("Database:Host");
  52. cfg.Remove("Database:Port");
  53. await cfg.SaveAsync();
  54. Console.WriteLine(" 已清理测试配置");
  55. cfg.Dispose();
  56. Console.WriteLine("\n[示例 9 完成]\n");
  57. }
  58. catch (Exception ex)
  59. {
  60. Console.WriteLine($" [跳过] Redis 服务不可用: {ex.Message}");
  61. Console.WriteLine("\n[示例 9 跳过]\n");
  62. }
  63. }
  64. }