平安校园
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.
 
 
 
 
 
 

51 line
2.3 KiB

  1. namespace SafeCampus.Cache;
  2. /// <summary>
  3. /// AppStartup启动类
  4. /// </summary>
  5. [AppStartup(97)]
  6. public class Startup : AppStartup
  7. {
  8. /// <summary>
  9. /// ConfigureServices中不能解析服务,比如App.GetService(),尤其是不能在ConfigureServices中获取诸如缓存等数据进行初始化,应该在Configure中进行
  10. /// 服务都还没初始化完成,会导致内存中存在多份 IOC 容器!!
  11. /// 正确应该在 Configure 中,这个时候服务(IServiceCollection 已经完成 BuildServiceProvider() 操作了
  12. /// </summary>
  13. /// <param name="services"></param>
  14. public void ConfigureServices(IServiceCollection services)
  15. {
  16. //缓存设置配置转实体
  17. services.AddConfigurableOptions<CacheSettingsOptions>();
  18. //禁止在主机启动时通过 App.GetOptions<TOptions> 获取选项,如需获取配置选项理应通过 App.GetConfig<TOptions>("配置节点", true)。
  19. var cacheSettings = App.GetConfig<CacheSettingsOptions>("CacheSettings", true);
  20. //如果有redis连接字符串
  21. if (cacheSettings.UseRedis)
  22. {
  23. //var connectionString = $"server={cacheSettings.RedisSettings.Address};password={cacheSettings.RedisSettings.Password};db={cacheSettings.RedisSettings.Db}";
  24. var connectionString = $"server={cacheSettings.RedisSettings.Address};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. }