surging icon indicating copy to clipboard operation
surging copied to clipboard

如何使用拦截器

Open fanliang11 opened this issue 6 years ago • 6 comments

surging 支持AOP远程和本地调用拦截,可以按照如下方式使用拦截器

如何创建拦截器

继承IInterceptor ,创建拦截,如下代码所示

public class LogProviderInterceptor : IInterceptor
    {
        public async Task Intercept(IInvocation invocation)
        { 
            await invocation.Proceed();
            var result = invocation.ReturnValue;
        }
    }

服务引擎针对于IInterceptor 扩展了CacheInterceptor用来做缓存拦截,如以下代码所示

  public class CacheProviderInterceptor : CacheInterceptor
    {
        public override async Task Intercept(ICacheInvocation invocation)
        { 
        }
}

如何使用缓存拦截器

通过特性Command中的RequestCacheEnabled 开启缓存拦截,如以下代码所示

[Command(RequestCacheEnabled = true)]

通过设置特性InterceptMethodAttribute配置缓存拦截,如以下代码所示

 [InterceptMethod(CachingMethod.Get, Key = "GetUser_id_{0}", CacheSectionType = SectionType.ddlCache, Mode = CacheTargetType.Redis, Time = 480)]

在处理业务的修改,删除方法时候,需要移除依赖的缓存,那么可以设置CorrespondingKeys,如以下代码所示

 [InterceptMethod(CachingMethod.Remove, "GetUser_id_{0}", "GetUserName_name_{0}", CacheSectionType = SectionType.ddlCache, Mode = CacheTargetType.Redis)]

如何设置缓存Key

1.比如缓存设置为GetUserById_{0}, 传递的参数是int 类型,值为2199 ,那么产生的key就是GetUserById_2199.

2.比如缓存设置为GetUser_{0}_{1},传递的参数是UserModel类型,传递为new UserModel{ UserId=2199,Name="Fanly" }值,那么产生的Key就是GetUser_fanly_2199. 标识CacheKeyAttribute特性以生成缓存key, 并且设置SortIndex排序依次生成。

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

        public int Age { get; set; }

    }

创建拦截模块

通过以下代码,把拦截器注入到服务引擎中

    public class IntercepteModule : SystemModule
    {
        public override void Initialize(CPlatformContainer serviceProvider)
        {
            base.Initialize(serviceProvider);
        }

        /// <summary>
        /// Inject dependent third-party components
        /// </summary>
        /// <param name="builder"></param>
        protected override void RegisterBuilder(ContainerBuilderWrapper builder)
        {
            base.RegisterBuilder(builder);
            builder.AddClientIntercepted(typeof(CacheProviderInterceptor),typeof(LogProviderInterceptor));
        }
    }

提示:大家可以按照自己的业务需求,研发缓存拦截,不一定非要使用CacheProviderInterceptor

fanliang11 avatar Aug 30 '18 07:08 fanliang11

用PostMan通过网关调用对应服务的接口,缓存拦截不起作用?但是通过RPC内部调用缓存拦截就有起作用,请问为啥?

qq 20180910175232redis @fanliang11

MrXuHuiFeng avatar Sep 10 '18 09:09 MrXuHuiFeng

网关没有引用接口,所以网关是不支持缓存拦截的,只有服务内部之间的调用可以启用缓存拦截

fanliang11 avatar Sep 10 '18 10:09 fanliang11

能考虑网关支持缓存拦截?老大有什么好建议? @fanliang11

MrXuHuiFeng avatar Sep 10 '18 10:09 MrXuHuiFeng

可以使用引擎的http协议

fanliang11 avatar Sep 10 '18 14:09 fanliang11

有http协议的使用文档吗?谢谢! @fanliang11

MrXuHuiFeng avatar Sep 11 '18 05:09 MrXuHuiFeng

"可以使用引擎的http协议" 老大,这个方案能否详细点说明? @fanliang11

huisenzhou avatar Feb 18 '19 09:02 huisenzhou