首页 > 其他分享 >NetCore Ocelot 之 Cache

NetCore Ocelot 之 Cache

时间:2023-10-09 15:56:56浏览次数:45  
标签:key cacheKey cacheObj NetCore region Cache cache Ocelot

Ocelot supports some very rudimentary caching at the moment provider by the CacheManager project. This s an amazing project that is solving a lot of caching problems. I would recommend using this package to cache with Ocelot.

The following example shows how to add CacheManager to Ocelot so that you can do output caching.

First of all add the following NuGet package.

Install-Package Ocelot.Cache.CacheManager

This will give you access to the Ocelot cache manager extension methods.

The second thing you need to do something like the following to your ConfigureService.

builder.Services.AddOcelot()
    .AddCacheManager(c => c.WithDictionaryHandle())// cache manager
    .AddSingletonDefinedAggregator<CustomAdvancedAggregator>()
    .AddCustomLoadBalancer((serviceProvider, route, serviceDiscoveryProvider) => new CustomRandomLoadBalancer(serviceDiscoveryProvider.Get))
    .AddConsul()
    .AddPolly().

Finally in order to use caching on a route in your Route configuration add this setting.

 "FileCacheOptions": {
        "TtlSeconds": 10,
        "Region": "gatewaycacheregion"
      }

In this example ttl seconds is set to 10 which means the cache will expire after 15 seconds.

Anyway Ocelot currently supports caching on the URL of the downstream service and setting a TTL in seconds to expire the cache. You can also clear the cache for a region by calling Ocelot's administartion API.

The result is whin 10 seconds the result always same due to the cache e.g.

  If you want to add your own caching method implement the following interface and register them in DI.

IOcelotCache<CacheResponse> this is for output caching.

IOcelotCache<FileConfiguration> this is for caching the file configuration if you are calling something remote to get your config such as Consul.

My custom cache impletemant IOcelotCache<CacheResponse>

    public class CustomCache : IOcelotCache<CachedResponse>
    {
        private static Dictionary<string, CacheObj> _cacheObj = new Dictionary<string, CacheObj>();
        public void Add(string key, CachedResponse value, TimeSpan ttl, string region)
        {
            var cacheKey = $"{region}_{key}";
            if (!_cacheObj.ContainsKey(cacheKey))
                _cacheObj.Add(cacheKey, new CacheObj()
                {
                    ExpireTime = DateTime.Now.Add(ttl),
                    Response = value,
                });
        }

        public void AddAndDelete(string key, CachedResponse value, TimeSpan ttl, string region)
        {
            var cacheKey = $"{region}_{key}";
            if (_cacheObj.ContainsKey(cacheKey))
                _cacheObj.Remove(cacheKey);
            _cacheObj.Add(cacheKey, new CacheObj()
            {
                ExpireTime = DateTime.Now.Add(ttl),
                Response = value,
            });
        }

        public void ClearRegion(string region)
        {
            var cacheKeys = _cacheObj.Where(o => o.Key.StartsWith(region)).Select(o => o.Key);
            foreach (var key in cacheKeys)
                _cacheObj.Remove(key);
        }

        public CachedResponse Get(string key, string region)
        {
            var cacheKey = $"{region}_{key}";
            if (!_cacheObj.ContainsKey(cacheKey)) return null;
            var cacheObj = _cacheObj[cacheKey];
            if (cacheObj != null && cacheObj.ExpireTime >= DateTime.Now)
                return cacheObj.Response;
            _cacheObj.Remove(cacheKey);
            return null;
        }

        internal class CacheObj
        {
            public DateTime ExpireTime { get; set; }
            public CachedResponse Response { get; set; }
        }
    }

Add CustomCache to DI

builder.Services.AddSingleton<IOcelotCache<CachedResponse>, CustomCache>();

The result is same as above.

标签:key,cacheKey,cacheObj,NetCore,region,Cache,cache,Ocelot
From: https://www.cnblogs.com/qindy/p/17751950.html

相关文章

  • NetCore Ocelot 之 Authorization
    Ocelotsupportsclaimsbasedauthorizationwhichisrunpostauthentication.ThismeansifouhavearouteyouwanttoauthorizeyoucanaddthefollowingtoyouRouteconfiguration."RouteClaimsRequirement":{"client_role":......
  • laravel8对接阿里云sdk刷新cdn缓存接口RefreshObjectCaches
    <?phpnamespaceApp\Admin\Forms;useEncore\Admin\Widgets\Form;useIlluminate\Http\Request;useAlibabaCloud\Client\AlibabaCloud;useAlibabaCloud\Client\Exception\ClientException;useAlibabaCloud\Client\Exception\ServerException;......
  • NetCore Ocelot 之 Qos
    QosqualityofserviceOcelotsupportsoneQoscapabilityatthecurrenttime.YoucansetonaperRoutebasisifyouwanttouseacircuitbreakerwhenmakingrequeststoadownstreamservice.Thisusesanawesome.NETlibrarycalledPolly.Thefirstthi......
  • NetCore Ocelot 之 Load Balancer
    OcelotcanloadbalanceacrossavailabledownstreamservicesforeachRoute.ThismeansyoucanscaleyourdownstreamservicesandOcelotcanusethemeffectively.TheTypeofloadbalanceravailbleare:  LeastConnection -trackswhichservicearedeal......
  • NetCore Ocelot 之 Authentication
    InordertoauthenticateRoutesandsubsequentlyuseanyofOcelot'sclaimsbasedfeaturessuchasauthorizationormodifyingtherequestwithvaluesfromthetoken.UsersmustregisterauthenticationservicesintheirStartup.csasusualbuttheypr......
  • NetCore Ocelot 之 Rate Limiting
    Ocelotsupportsratelimitingofupstreamrequestssothatyourdownstreamservicesdonotbecomeoverloaded.OKsotogetratelimitingworkingforaRouteyouneedtoaddthefollowingjsontoit."RateLimitOptions":{"ClientWhi......
  • 简述memcached的工作原理
     Memcached只支持能序列化的数据类型,不支持持久化,基于Key-Value的内存缓存系统1.内存分配机制 应用程序运行需要使用内存存储数据,但对于一个缓存系统来说,申请内存、释放内存将十分频繁,非常容易导致大量内存碎片,最后导致无连续可用内存可用。 Memcached采用了Slab......
  • NetCore学习笔记:单元测试和集成测试
    前言#我在使用AspNetCore的这段时间内,看了很多开源项目和博客,发现各种.Net体系的新技术很多人都有关注和使用,但却很少有人关注测试。测试是软件生命周期中的一个非常重要的阶段,对于保证软件的可靠性具有极其重要的意义。在应用程序的开发过程中,为了确保它的功能与预期一致,......
  • django-celery-results - 使用 Django ORM/Cache 作为结果后端
    https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html#django-celery-results-using-the-django-orm-cache-as-a-result-backend这个一般自己设置一下result_backend也行,要用django-celery-results也是一个选择。......
  • 开源.NetCore通用工具库Xmtool使用连载 - 扩展动态对象篇
    【Github源码】《上一篇》介绍了Xmtool工具库中的图形验证码类库,今天我们继续为大家介绍其中的扩展动态对象类库。<br>扩展动态对象是整个工具库中最重要的一个设计。在软件开发过程中,我们经常需要定义各种各样的数据对象;例如:用于参数传递的数据实体类、用于接口返回结果的Json......