平安校园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

преди 3 месеца
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 
  2. namespace SafeCampus.Cache;
  3. /// <summary>
  4. /// AppStartup启动类
  5. /// </summary>
  6. [AppStartup(97)]
  7. public class Startup : AppStartup
  8. {
  9. /// <summary>
  10. /// ConfigureServices中不能解析服务,比如App.GetService(),尤其是不能在ConfigureServices中获取诸如缓存等数据进行初始化,应该在Configure中进行
  11. /// 服务都还没初始化完成,会导致内存中存在多份 IOC 容器!!
  12. /// 正确应该在 Configure 中,这个时候服务(IServiceCollection 已经完成 BuildServiceProvider() 操作了
  13. /// </summary>
  14. /// <param name="services"></param>
  15. public void ConfigureServices(IServiceCollection services)
  16. {
  17. //缓存设置配置转实体
  18. services.AddConfigurableOptions<CacheSettingsOptions>();
  19. //禁止在主机启动时通过 App.GetOptions<TOptions> 获取选项,如需获取配置选项理应通过 App.GetConfig<TOptions>("配置节点", true)。
  20. var cacheSettings = App.GetConfig<CacheSettingsOptions>("CacheSettings", true);
  21. //如果有redis连接字符串
  22. if (cacheSettings.UseRedis)
  23. {
  24. var connectionString = $"server={cacheSettings.RedisSettings.Address};password={cacheSettings.RedisSettings.Password};db={cacheSettings.RedisSettings.Db}";
  25. //注入redis
  26. //var connectionString = "server=127.0.0.1:6379;password=sxtbxx;db=1";
  27. services.AddSimpleRedis(connectionString);
  28. services.AddSingleton<ISimpleCacheService, RedisCacheService>();
  29. }
  30. else
  31. {
  32. services.AddSingleton<ISimpleCacheService, MemoryCacheService>();
  33. }
  34. }
  35. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  36. {
  37. //通过 App.GetOptions<TOptions> 获取选项
  38. var cacheSettings = App.GetOptions<CacheSettingsOptions>();
  39. //如果需要清除缓存
  40. if (cacheSettings.UseRedis && cacheSettings.RedisSettings.ClearRedis)
  41. {
  42. var redis = App.GetService<ISimpleCacheService>();//获取redis服务
  43. //删除redis的key
  44. redis.DelByPattern(CacheConst.CACHE_PREFIX_WEB);
  45. }
  46. }
  47. }