MasaFramework -- 缓存入门与规则配置( 三 )

  1. 注册分布式Redis缓存
builder.Services.AddDistributedCache(distributedCacheOptions =>{distributedCacheOptions.UseStackExchangeRedisCache();});方案四. 通过指定Configuration注册
  1. 在Redis缓存的配置存储到本地appsettings.json文件
{"RedisConfig":{"Servers":[{"Host": "localhost","Port": 6379}],"DefaultDatabase": 3,"ConnectionPoolSize": 10}}
  1. 指定Configuration注册分布式Redis缓存
var builder = WebApplication.CreateBuilder(args);//注册分布式缓存builder.Services.AddDistributedCache(distributedCacheOptions =>{// 使用存储Redis配置的ConfigurationdistributedCacheOptions.UseStackExchangeRedisCache(builder.Configuration.GetSection("RedisConfig"));});方案五. 将配置存储到Dcc上,并通过Configuration提供的手动映射功能,实现选项模式
  1. 使用Dcc,并手动指定映射
builder.AddMasaConfiguration(configurationBuilder =>{configurationBuilder.UseDcc();//使用Dcc 扩展Configuration能力,支持远程配置configurationBuilder.UseMasaOptions(options =>{//通过手动映射RedisConfigurationOptions的配置,实现选项模式options.MappingConfigurationApi<RedisConfigurationOptions>("{替换为Dcc中配置所属的AppId}", "{替换为Redis配置的对象名称}");});});
  1. 注册分布式Redis缓存
builder.Services.AddDistributedCache(distributedCacheOptions =>{distributedCacheOptions.UseStackExchangeRedisCache();});
方案三、四、五的本质都是通过支持选项模式来注册分布式Redis缓存
修改缓存Key映射规则修改缓存Key映射规则十分简单,我们在配置时更改CacheKeyType为对应的规则即可,但当 CacheKeyType = 3 需要注意,它需要额外提供类型名与别名的对应关系,完整例子如下:
  1. 修改appsettings.json, 将CacheKeyType的值改为 3
{"RedisConfig":{"Servers":[{"Host":"localhost","Port":6379}],"DefaultDatabase":3,"ConnectionPoolSize":10,"GlobalCacheOptions": {"CacheKeyType": 3 //CacheKeyType为3时启用别名格式化缓存Key,可节省缓存Key的键长度}}}
  1. 注册分布式缓存并配置类型名与别名的对应关系
builder.Services.AddDistributedCache(distributedCacheOptions =>{distributedCacheOptions.UseStackExchangeRedisCache();}, typeAliasOptions =>{typeAliasOptions.GetAllTypeAliasFunc = () => new Dictionary<string, string>(){{ "String", "s" }//当类型为String时,格式化后的Key为 s:key};});
通过指定类型与别名的对应关系,从而使得最终形成较短的缓存Key,以达到节省存储空间的目的,缓存Key生成规则可查看
多级缓存示例多级缓存注册方案一. 通过本地配置文件注册
  1. 修改appsettings.json文件,分别配置多级缓存配置以及Redis缓存配置
{// 多级缓存全局配置,非必填"MultilevelCache": {"SubscribeKeyPrefix": "masa",//默认订阅方key前缀,用于拼接channel"SubscribeKeyType": 3, //默认订阅方key的类型,默认ValueTypeFullNameAndKey,用于拼接channel"CacheEntryOptions": {"AbsoluteExpirationRelativeToNow": "00:00:30",//绝对过期时长(距当前时间)"SlidingExpiration": "00:00:50"//滑动过期时长(距当前时间)}},// Redis分布式缓存配置"RedisConfig": {"Servers": [{"Host": "localhost","Port": 6379}],"DefaultDatabase": 3}}
  1. 添加多级缓存并使用分布式Redis缓存
builder.Services.AddMultilevelCache(distributedCacheOptions =>{distributedCacheOptions.UseStackExchangeRedisCache();});方案二. 通过手动指定配置
builder.Services.AddMultilevelCache(distributedCacheOptions =>{distributedCacheOptions.UseStackExchangeRedisCache(RedisConfigurationOptions);});

经验总结扩展阅读