平安校园
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 месеци
пре 3 месеци
пре 3 месеци
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. var connectionString = $"server={cacheSettings.RedisSettings.Address};db={cacheSettings.RedisSettings.Db}";
  26. //注入redis
  27. //var connectionString = "server=127.0.0.1:6379;password=sxtbxx;db=1";
  28. services.AddSimpleRedis(connectionString);
  29. services.AddSingleton<ISimpleCacheService, RedisCacheService>();
  30. }
  31. else
  32. {
  33. services.AddSingleton<ISimpleCacheService, MemoryCacheService>();
  34. }
  35. }
  36. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  37. {
  38. //通过 App.GetOptions<TOptions> 获取选项
  39. var cacheSettings = App.GetOptions<CacheSettingsOptions>();
  40. //如果需要清除缓存
  41. if (cacheSettings.UseRedis && cacheSettings.RedisSettings.ClearRedis)
  42. {
  43. var redis = App.GetService<ISimpleCacheService>();//获取redis服务
  44. //删除redis的key
  45. redis.DelByPattern(CacheConst.CACHE_PREFIX_WEB);
  46. }
  47. }
  48. }