(五)surging 微服务框架使用系列之缓存-reids

1.服务跟客户端初始化的时候需要添加缓存配置

 1            var host = new ServiceHostBuilder()
 2                 .RegisterServices(builder =>
 3                 {
 4                     builder.AddMicroService(option =>
 5                     { 6               option .AddCache()//缓存初始化28              });29                 }).Configure(build =>47                   build.AddCacheFile("cacheSettings.json", optional: false,reloadOnChange:true))48                 .UseStartup<Startup>()52                 .Build();

2.配置文件(服务端跟客户端都需要)

{
  "CachingSettings": [
    {
      "Id": "ddlCache",
      "Class": "Surging.Core.Caching.RedisCache.RedisContext,Surging.Core.Caching",
      "InitMethod": "",
      "Maps": null,
      "Properties": [
        {
          "Name": "appRuleFile",
          "Ref": "rule",
          "Value": "",
          "Maps": null
        },
        {
          "Name": "dataContextPool",
          "Ref": "ddls_sample",
          "Value": "",
          "Maps": [
            {
              "Name": "Redis",//redis配置
              "Properties": [
                {
                  "Name": null,
                  "Ref": null,
                  "Value": ":你的密码@你的ip:6379::1",//reids 内存数据库连接字符串传 后面的1 代表你当前连接的是哪个库
                  "Maps": null
                }
              ]
            },
            {
              "Name": "MemoryCache",//本机内存
              "Properties": null
            }
          ]
        },
        {
          "Name": "defaultExpireTime",//默认超时时间
          "Ref": "",
          "Value": "120",
          "Maps": null
        },
        {
          "Name": "connectTimeout",//连接超时时间
          "Ref": "",
          "Value": "120",
          "Maps": null
        },
        {
          "Name": "minSize",
          "Ref": "",
          "Value": "1",
          "Maps": null
        },
        {
          "Name": "maxSize",
          "Ref": "",
          "Value": "10",
          "Maps": null
        }
      ]
    }
  ]
}

3.服务端配置

[Command(RequestCacheEnabled = true)]
[InterceptMethod(CachingMethod.Get, Key = "GetUser_id_{0}", CacheSectionType = SectionType.ddlCache, Mode = CacheTargetType.Redis, Time = 480)]
Task<UserModel> GetUser(UserModel user);

(1)在容错规则里面配置开启缓存

(2)在缓存拦截器里面配置缓存的方法,key,类型,超时时间等等。。

(3)传递的方法参数如果是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,传递的方法参数是string,int 类型就不需要设置 [CacheKey(1)]

(4)Remove模式下,移除的缓存是一个真个列表

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

4.客户端调用配置

客户端初始化的时候  需要添加.AddClientIntercepted(typeof(CacheProviderInterceptor)),其中CacheProviderInterceptor是作者给我们实现的一个实例,代码如下:

public class CacheProviderInterceptor : CacheInterceptor
    {
        public override async Task Intercept(ICacheInvocation invocation)
        {
            var attribute =
                 invocation.Attributes.Where(p => p is InterceptMethodAttribute)
                 .Select(p => p as InterceptMethodAttribute).FirstOrDefault();
            var cacheKey = invocation.CacheKey == null ? attribute.Key :
                string.Format(attribute.Key ?? "", invocation.CacheKey);
            await CacheIntercept(attribute, cacheKey, invocation);
        }

        private async Task CacheIntercept(InterceptMethodAttribute attribute, string key, ICacheInvocation invocation)
        {
            ICacheProvider cacheProvider = null;
            switch (attribute.Mode)
            {
                case CacheTargetType.Redis:
                    {
                        cacheProvider = CacheContainer.GetService<ICacheProvider>(string.Format("{0}.{1}",
                           attribute.CacheSectionType.ToString(), CacheTargetType.Redis.ToString()));
                        break;
                    }
                case CacheTargetType.MemoryCache:
                    {
                        cacheProvider = CacheContainer.GetService<ICacheProvider>(CacheTargetType.MemoryCache.ToString());
                        break;
                    }
            }
            if (cacheProvider != null) await Invoke(cacheProvider, attribute, key, invocation);
        }

        private async Task Invoke(ICacheProvider cacheProvider, InterceptMethodAttribute attribute, string key, ICacheInvocation invocation)
        {
            switch (attribute.Method)
            {
                case CachingMethod.Get:
                    {
                        var retrunValue = await cacheProvider.GetFromCacheFirst(key, async () =>
                        {
                            await invocation.Proceed();
                            return invocation.ReturnValue;
                        }, invocation.ReturnType, attribute.Time);
                        invocation.ReturnValue = retrunValue;
                        break;
                    }
                default:
                    {
                        await invocation.Proceed();
                        var keys = attribute.CorrespondingKeys.Select(correspondingKey => string.Format(correspondingKey, invocation.CacheKey)).ToList();
                        keys.ForEach(cacheProvider.RemoveAsync);
                        break;
                    }
            }
        }
    }

找到InterceptMethodAttribute 的配置属性根据配置的缓存类型  初始化ICacheProvider接口,这个接口是缓存的一些常用方法,(当然我们也直接可以在代码中或者这个接口的实例,从而在缓存计算一些值)

然后在Invoke方法里面执行缓存的方法

5.其他

关于缓存拦截  我目前的版本是0.7.0.1 是只能在调用代理的时候用使用。因为在代理的时候才会根据容错规则开启缓存开关 来决定执行是否走缓存拦截。新版本的http支持 实现了缓存拦截。所以有需要的小伙伴可以升个级试试看。

关于缓存的连接  也是通过注册中心来检查它的健康状态。

最后运行程序,得到结果

原文地址:https://www.cnblogs.com/Jeely/p/10774648.html

时间: 2024-08-30 16:38:12

(五)surging 微服务框架使用系列之缓存-reids的相关文章

(二)surging 微服务框架使用系列之surging 的准备工作consul安装

suging 的注册中心支持consul跟zookeeper.因为consul跟zookeeper的配置都差不多,所以只是consul的配置 consul下载地址:https://www.consul.io/downloads.html consul agent 命令的常用选项,如下: -data-dir 作用:指定agent储存状态的数据目录 这是所有agent都必须的 对于server尤其重要,因为他们必须持久化集群的状态 -config-dir  作用:指定service的配置文件和检查定

基于.NET CORE微服务框架 -浅析如何使用surging

1.前言 surging受到大家这么强烈的关注,我感到非常意外,比如有同僚在公司的分享会上分享surging, 还有在博客拿其它的RPC框架,微服务做对比等等,这些举动都让我感觉压力很大,毕竟作为个人的开源项目,无法与成熟的开源社区的项目相比,也只有等到后面有许许多多志同道合的朋友加入一起研发完善surging,这样才能让surging 成为流行的微服务框架. 这篇文章介绍如何使用surging 开源地址:https://github.com/dotnetcore/surging 2.设计模式

微服务框架surging学习之路——序列化

原文:微服务框架surging学习之路--序列化 1.对微服务的理解 之前看到在群里的朋友门都在讨论微服务,看到他们的讨论,我也有了一些自己的理解,所谓微服务就是系统里的每个服务都 可以自由组合.自由组合这个就很厉害了,这样一来,每个服务与服务之间基本的物理 耦合为0,横向扩展整个系统就会非常非常灵活. surging的厉害之处也恰恰是可以做到这些,所以surging 是.net core 里面一个非常不错的微服务框架. 2.surging的序列化方式 2.1 json.Net surging

[转帖]微服务框架Spring Cloud介绍 Part2: Spring Cloud与微服务

微服务框架Spring Cloud介绍 Part2: Spring Cloud与微服务 http://skaka.me/blog/2016/08/03/springcloud2/ AUG 3RD, 2016 10:09 PM | COMMENTS 之前介绍过微服务的概念与Finagle框架, 这个系列介绍Spring Cloud. Spring Cloud还是一个相对较新的框架, 今年(2016)才推出1.0的release版本. 虽然Spring Cloud时间最短, 但是相比我之前用过的Du

日调度万亿次,微服务框架TSF大规模应用——云+未来峰会开发者专场回顾

欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 演讲者:张浩 腾讯云中间件产品负责人 背景:众多开发者中,一定经历类似的甜蜜烦恼,就是当线上业务规模越来越大,系统分支发展越来越多的时候,初期上线的成就感很快就会被系统间数据不兼容.不通畅,折磨得精疲力尽,每次模块更新都是牵一发而动全身.腾讯云微服务框架TSF就可以为大家解决数据孤岛以及重复造轮子的问题,提供了简洁易用的代码入口,将复杂的底层网络.服务器部署接口化,使开发者更易用. 本文整理自腾讯云中间件产品负责人张浩在腾讯云云+未来峰

微服务框架-SpringCloud简介

前面一篇文章谈到微服务基础框架,而Netflix的多个开源组件一起正好可以提供完整的分布式微服务基础架构环境,而对于Spring Cloud正是对Netflix的多个开源组件进一步的封装而成,同时又实现了和云端平台,和Spring Boot开发框架很好的集成. Spring Cloud是一个相对比较新的微服务框架,今年(2016)才推出1.0的release版本. 虽然Spring Cloud时间最短, 但是相比Dubbo等RPC框架, Spring Cloud提供的全套的分布式系统解决方案.

AG-Admin微服务框架入门

AG-Admin微服务框架入门  @qq群:一群: 837736451  二群 169824183 一 概要介绍 AG-Admin后台地址:https://gitee.com/minull/ace-security AG-Admin前端地址:https://gitee.com/minull/AG-Admin-v2.0 要想玩儿转spring cloud必须进行一大波儿的学习哦,先有个心理准备. AG-Admin基于Spring Cloud微服务化开发平台,具有统一授权.认证微服务云框架.其中包含

一个微服务框架的细节

KingWorks微服务系列文章: (一)一个微服务框架的故事 (二)一个微服务框架的情节 从KingWorks-0.0.0版本(想象版本)开始,我就知道我踏上了一条"不归的自主研发路线",到目前的KingWorks-3.0.0,我始终坚守着这一份执着.曾经想过放弃,因为它不是"开源主流":曾经想过放弃,因为它很费力:曾经想过放弃,因为为了让它生命力不断,我需要付出的精力比专研几个新框架还要累得累.我坚守了,是因为它的简单:我坚守了,是因为同事们的喜欢:我坚守了,是

go微服务框架go-micro深度学习-目录

go微服务框架go-micro深度学习(一) 整体架构介绍 go微服务框架go-micro深度学习(二) 入门例子 go微服务框架go-micro深度学习(三) Registry服务的注册和发现 go微服务框架go-micro深度学习(四) rpc方法调用过程详解 go微服务框架go-micro深度学习(五) stream 调用过程详解 代码在github上 原文地址:https://www.cnblogs.com/li-peng/p/10522084.html