Skip to content

Surging 缓存拦截配置示例

billyang edited this page Apr 3, 2018 · 1 revision

Surging 其中一个很强大的功能是支持缓存拦截,这可能是对别的为微服务框架来讲,Surging一个非常具有吸引力的特点。

引用Surging作者的原话

第一步: 首先需要新建缓存的配置文件cacheSettings.json
cacehesetting.json :
1: 配置部分“CachingSettings”属性“Id”是ICacheProvider实例ID
2: 配置部分“Maps”属性“Name”是什么缓存
3: 配置部分“Maps”属性 Properties是一个缓存服务器列表
4: 配置节“Properties”属性“defaultExpireTime”的值为120是缓存默认丢失有效时间为120秒
5: 配置节“Properties”属性“connectTimeout”值为120的连接缓存服务器超时时间为120秒
6: 配置节“Properties”属性“minSize”的值为1,最小线程池为1
7: 配置节“Properties” 属性的“maxSize”值为10,最大线程池为10

第二步: 1:设置缓存配置文件

 .Configure(build => build.AddCacheFile("cacheSettings.json", optional: false, reloadOnChange: true))

2 缓存节点注册:配置UseServiceCache() 启动服务时,注册到注册中心

3:设置心跳方式更新配置文件

     option.AddConfigurationWatch();

第三步: 1:配置服务拦截

  option.AddClientIntercepted(typeof(CacheProviderInterceptor));

怎么使用分布式缓存

  1. 在接口方法上添加以下特性开启缓存 [Command( RequestCacheEnabled = true)]
  2. 在接口方法上添加以下特性 设置拦截 [InterceptMethod(CachingMethod.Get, Key = "GetUser_id_{0}", CacheSectionType = SectionType.ddlCache, Mode = CacheTargetType.Redis, Time = 480)] 以下是针对于特性参数的介绍

CachingMethod.Get, 缓存获取 CachingMethod.Put, 缓存更新 CachingMethod.Remove 缓存删除 Key 缓存键值, CacheSectionType 配置节类型 Mode 采用什么方式缓存 Time 缓存的失效时间

在需要配置缓存拦截的接口方法中配置

[Command(Strategy = StrategyType.Failover, RequestCacheEnabled = true, InjectionNamespaces = new string[] { "Bill.Demo.IModuleServices.Users" })]
[InterceptMethod(CachingMethod.Get, Key = "GetUser_id_{0}", CacheSectionType = SectionType.ddlCache, Mode = CacheTargetType.Redis, Time = 480)]
Task<UserDto> GetUserById(Int64 id);


[Command(Strategy = StrategyType.Failover, RequestCacheEnabled = true, InjectionNamespaces = new string[] { "Bill.Demo.IModuleServices.Users" })]
[InterceptMethod(CachingMethod.Remove, "GetUser_id_{0}", CacheSectionType = SectionType.ddlCache, Mode = CacheTargetType.Redis)]
Task<Boolean> DeleteUser(Int64 userId);

1.传递的方法参数如果是model类型,就需要设置 [CacheKey(1)]来标识缓存key, 比如传递UserModel,设置UserId 为1,Name 为fanly,
设置的KEY为GetUserName_name_{1},那么缓存的key就会生成GetUserName_name_fanly;
key 如果设置为GetUserName_id_{0},那么缓存的key就会生成GetUserName_id_1
2. 传递的方法参数是string,int 类型就不需要设置 [CacheKey(1)]

   [ProtoContract]
   public class UserModel
   {
       [CacheKey(1)]
       public int UserId { get; set; }
       [CacheKey(2)]
       public string Name { get; set; }
       public int Age { get; set; }

   }

通过Redis客户端查看Redis数据
当执行Get时,可以通过Redis查询到surging已经成功将数据拦截到了Redis中

127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> keys *
1) "_ddlCache_GetUser_id_6"
2) "_ddlCache_GetUser_id_2"

执行Remove时, surging删除了Redis缓存

127.0.0.1:6379[1]> keys *
1) "_ddlCache_GetUser_id_2"
127.0.0.1:6379[1]>
Clone this wiki locally