SlideShare a Scribd company logo
www.xedotnet.org
Andrea Dottor
Microsoft MVP Visual Studio and Development Technologies
@dottor
Ottimizzare con la CACHE
DEMO
Cache, questa sconosciuta
• Da wikipedia: "Con il termine cache in
informatica si indica un'area di memoria
estremamente veloce ma solitamente di un basso
ordine di grandezza di capacità. Il suo scopo è
di velocizzare l'esecuzione dei programmi."
• Da Microsoft/Architecture/Best Practices: "Caching
can dramatically improve performance,
scalability, and availability. "
Quando è utile la cache
Quando la gran parte degli utenti accede agli stessi dati
Quando abbiamo informazioni che non cambiano spesso
Quando il database è il "collo di bottiglia"
Quando si hanno (gli stessi) dati che
vengono letti di frequente
Cosa salvare in cache
Dati di lookup/tabellare, che non cambiano spesso
Comuni, professioni, categorie, voci di menu, …
Dati che sono il risultato di query/elaborazioni che
vengono richiesti spesso
Nel caso di grafi/elementi complessi è pensabile
salvare in cache anche solo una porzione
Tipologie di cache
Tipologie di cache - InProc
InProc
• System.Web.Caching
• System.Runtime.Cache
• IMemoryCache
Viene utilizzata da un unico applicativo
Parte della memoria utilizzata dall'applicazione viene
utilizzata per salvare i dati della cache
System.Runtime.Cache
• Presente dal .NET Framework 4
• Unione tra la cache di ASP.NET
(System.Web.Caching) e il Caching Application Block
della Enterprise Library
• Possibilità di essere utilizzata in applicazioni non
web
• Nessuna dipendenza con System.Web 
• Non esiste più la SqlDependency per invalidare la
cache
IMemoryCache
• Implementazione della cache InProc per ASP.NET Core
• In ASP.NET Core 2 è già configurata di default
• In ASP.NET Core 1 se ne deve specificare l'uso in fase
di startup
DEMO
InMemory cache
Tipologie di cache - distribuita
Cache distribuita / Application cache
• Redis
• Memcached
• SQL Server
• …
Utile in quanto può essere condivisa tra più applicativi,
che possono anche risiedere su server differenti
Il riavvio di un applicativo non causa la perdita dei dati
in cache
Redis
"Redis is an open source (BSD licensed), in-memory data
structure store, used as a database, cache and message
broker. It supports data structures such as strings,
hashes, lists, sets, sorted sets with range queries,
bitmaps, hyperloglogs and geospatial indexes with radius
queries."
Database in-memory
Diventato famoso per la sue performance in quanto a
velocità di lettura/scrittura
Offre la possibilità di poter persistere i dati
https://redis.io/
Chocolatey e redis
• Installing Chocolatey
• https://chocolatey.org/install
Tramite powershell
• > choco install redis-64
• > redis-server
Redis client
A seconda del client scelto
• O fornisce metodi che lavorano con string o byte[]
• O fa uso dei Generics in modo da poter deserializzare gli
oggetti salvati e riportarli nel tipo corretto
• Che internamente si occupa di gestire solo string o byte[]
Per .NET Core esiste un client ufficiale Microsoft:
• Microsoft.Extensions.Caching.Redis
• Implementa IDistributedCache
Memcached
"Free & open source, high-performance, distributed
memory object caching system, generic in nature, but
intended for use in speeding up dynamic web applications
by alleviating database load.
Memcached is an in-memory key-value store for small
chunks of arbitrary data (strings, objects) from results
of database calls, API calls, or page rendering.
Memcached is simple yet powerful. Its simple design
promotes quick deployment, ease of development, and
solves many problems facing large data caches. Its API
is available for most popular languages."
Supporta il salvataggio solo di stringhe (o oggetti
serializzati)
Lavora solamente in memoria
https://memcached.org/
Memcached client
EnyimMemcached
• https://github.com/enyim/EnyimMemcached
• https://www.nuget.org/packages/EnyimMemcached/
Per .NETStandard 2.0
• https://www.nuget.org/packages/EnyimMemcachedCore
DEMO
Distribuited cache
Tipologie di cache - browser
Gestione headers:
• Cache-Control
• Pragma
• If-None-Match
• Etag
• If-Modified-Since
• Age
• …
Varie tecnologie:
• Output Cache
• Response Cache
• ETag
Riduzione del numero di richieste verso l'applicativo
Browser e/o proxy possono mantenere in cache una
copia dell'output della richiesta
Output cache
Permette il controllo dell'header Cache-Control
Permette di ridurre il numero di richieste verso il server
Possibilità di inserire in cache l'output di una pagina aspx
o di una chiamata ad un controller
Si risparmia il tempo di generazione
E' possibile parametrizzare la chiave con cui viene
inserire l'elemento in cache, in modo che possa
dipendere da vari fattori/parametri
• Querystring
• Utente
• Form input
• Lingua
ResponseCache
Implementata per ASP.NET Core in sostituzione dell'Output cache
Permette il controllo dell'header Cache-Control
Permette di ridurre il numero di richieste verso il server
ResponseCache a differenza dell'Output cache non salva l'html di
output ma gestisce solo l'header
!! Non attivo se presente "antiforgery"
!! Non attivo se header "authorization"
Cache per i file statici
E' possibile attivare lo stesso meccanismo del
Response Cache anche per i file statici
Si interviene manualmente nel metodo Configure
della classe Startup.
ETag
Permette di risparmiare il tempo di
traferimeto/download
Si basa sul ritornare un hash del contenuto
• Passato nell'header ETag
Ritornare un 304 Not Modified nel caso di request
con lo stesso hash (passato nell'header If-None-
Match)
DEMO
Response cache e Static file
Non è tutto oro quello che luccica
La serializzazione si paga
Il trasferimento dei dati si paga
Invalidare correttamente i dati non è cosa semplice
Serialization considerations
• Protocol Buffers (also called protobuf) is a serialization format
developed by Google for serializing structured data efficiently. It
uses strongly-typed definition files to define message structures.
• JSON is an open standard that uses human-readable text fields. It
has broad cross-platform support. JSON does not use message
schemas.
• BSON is a binary serialization format that uses a structure similar
to JSON. BSON was designed to be lightweight, easy to scan, and
fast to serialize and deserialize, relative to JSON. Payloads are
comparable in size to JSON. Depending on the data, a BSON
payload may be smaller or larger than a JSON payload. BSON has
some additional data types that are not available in JSON, notably
BinData (for byte arrays) and Date.
• MessagePack is a binary serialization format that is designed to
be compact for transmission over the wire. There are no message
schemas or message type checking.
• …
Links
• Microsoft Best Practices - Caching
• https://docs.microsoft.com/en-us/azure/architecture/best-practices/caching
• Per ASP.NET Core:
• In-memory caching
• https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory
• Distributed Cache
• https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed
• Cache Tag Helper
• https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/cache-tag-helper
• Distributed Cache Tag Helper
• https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/distributed-cache-tag-helper
• ResponseCache attribute
• https://docs.microsoft.com/en-us/aspnet/core/performance/caching/response
• ETag header in ASP.NET Core
• https://madskristensen.net/blog/send-etag-headers-in-aspnet-core/
Andrea Dottor
Email: andrea@dottor.net
Www: www.dottor.net
Twitter: @dottor

More Related Content

PDF
JBoss Data Grid Tech Lab
PDF
Data grid
PDF
Infinispan codemotion - Codemotion Rome 2015
PDF
Presentazione bd2
PDF
Hosting e la suddivisione delle risorse: le tecnologie #TipOfTheDay
PDF
Codemotion fuse presentation
PPTX
ASP.NET performance optimization
PPTX
Esempio di architettura distribuita basata su PHP, CouchDB e Mobile
JBoss Data Grid Tech Lab
Data grid
Infinispan codemotion - Codemotion Rome 2015
Presentazione bd2
Hosting e la suddivisione delle risorse: le tecnologie #TipOfTheDay
Codemotion fuse presentation
ASP.NET performance optimization
Esempio di architettura distribuita basata su PHP, CouchDB e Mobile

Similar to ASP.NET, ottimizziamo con la cache (20)

ODP
Memcached
PPTX
Mobile e Smart Client
PPTX
presentazione_Lelli_final
PPTX
Wcf data services
PPTX
Introduzione a DotNetNuke
PDF
Node and the Cloud
PDF
Stanco delle solite Web App? Passa al Prgressive
PPT
What's New in ASP.NET 4.5 and Visual Studio 2012
ODP
Net core base
ODP
Web Performance Optimization
PDF
Introduzione a node: cenni storici ecc
PDF
L'architettura di Stack Overflow - Mario Cecconi - Codemotion Milan 2014
PDF
Alfresco in un ora 2010
PDF
Alfresco Enterprise 3.4 ita
PDF
Creare API pubbliche, come evitare gli errori comuni
PDF
Redis - Non solo cache
PDF
ASP.NET Core Web Framework Benchmarks
PPT
Wp storage (online) - tiziano cacioppolini
PDF
Applicazioni HTML5 Superveloci - Salvatore Romeo
PDF
Stack Overflow - It's All About Performance - Marco Cecconi - Codemotion Roma...
Memcached
Mobile e Smart Client
presentazione_Lelli_final
Wcf data services
Introduzione a DotNetNuke
Node and the Cloud
Stanco delle solite Web App? Passa al Prgressive
What's New in ASP.NET 4.5 and Visual Studio 2012
Net core base
Web Performance Optimization
Introduzione a node: cenni storici ecc
L'architettura di Stack Overflow - Mario Cecconi - Codemotion Milan 2014
Alfresco in un ora 2010
Alfresco Enterprise 3.4 ita
Creare API pubbliche, come evitare gli errori comuni
Redis - Non solo cache
ASP.NET Core Web Framework Benchmarks
Wp storage (online) - tiziano cacioppolini
Applicazioni HTML5 Superveloci - Salvatore Romeo
Stack Overflow - It's All About Performance - Marco Cecconi - Codemotion Roma...
Ad

More from Andrea Dottor (20)

PDF
Blazor ♥️ JavaScript
PDF
Blazor, lo sapevi che...
PDF
Dal RenderFragment ai Generics, tips for Blazor developers
PDF
Blazor per uno sviluppatore Web Form
PDF
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
PDF
Blazor ha vinto? Storie di casi reali
PDF
What's New in ASP.NET Core 3
PDF
Alla scoperta di gRPC
PDF
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
PPTX
Real case: migrate from Web Forms to ASP.NET Core gradually
PDF
ASP.NET Core - Razor Pages
PDF
ASP.NET Core - dove siamo arrivati
PDF
Dependency injection questa sconosciuta
PPTX
Customize ASP.NET Core scaffolding
PPTX
Cosa c'è di nuovo in asp.net core 2 0
PPTX
Deploy & Run on Azure App Service
PPTX
ASP.NET Core
PDF
L'evoluzione del web
PPTX
Introduzione ad ASP.NET Core
PPTX
Sviluppare Azure Web Apps
Blazor ♥️ JavaScript
Blazor, lo sapevi che...
Dal RenderFragment ai Generics, tips for Blazor developers
Blazor per uno sviluppatore Web Form
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
Blazor ha vinto? Storie di casi reali
What's New in ASP.NET Core 3
Alla scoperta di gRPC
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
Real case: migrate from Web Forms to ASP.NET Core gradually
ASP.NET Core - Razor Pages
ASP.NET Core - dove siamo arrivati
Dependency injection questa sconosciuta
Customize ASP.NET Core scaffolding
Cosa c'è di nuovo in asp.net core 2 0
Deploy & Run on Azure App Service
ASP.NET Core
L'evoluzione del web
Introduzione ad ASP.NET Core
Sviluppare Azure Web Apps
Ad

ASP.NET, ottimizziamo con la cache

  • 1. www.xedotnet.org Andrea Dottor Microsoft MVP Visual Studio and Development Technologies @dottor Ottimizzare con la CACHE
  • 3. Cache, questa sconosciuta • Da wikipedia: "Con il termine cache in informatica si indica un'area di memoria estremamente veloce ma solitamente di un basso ordine di grandezza di capacità. Il suo scopo è di velocizzare l'esecuzione dei programmi." • Da Microsoft/Architecture/Best Practices: "Caching can dramatically improve performance, scalability, and availability. "
  • 4. Quando è utile la cache Quando la gran parte degli utenti accede agli stessi dati Quando abbiamo informazioni che non cambiano spesso Quando il database è il "collo di bottiglia" Quando si hanno (gli stessi) dati che vengono letti di frequente
  • 5. Cosa salvare in cache Dati di lookup/tabellare, che non cambiano spesso Comuni, professioni, categorie, voci di menu, … Dati che sono il risultato di query/elaborazioni che vengono richiesti spesso Nel caso di grafi/elementi complessi è pensabile salvare in cache anche solo una porzione
  • 7. Tipologie di cache - InProc InProc • System.Web.Caching • System.Runtime.Cache • IMemoryCache Viene utilizzata da un unico applicativo Parte della memoria utilizzata dall'applicazione viene utilizzata per salvare i dati della cache
  • 8. System.Runtime.Cache • Presente dal .NET Framework 4 • Unione tra la cache di ASP.NET (System.Web.Caching) e il Caching Application Block della Enterprise Library • Possibilità di essere utilizzata in applicazioni non web • Nessuna dipendenza con System.Web  • Non esiste più la SqlDependency per invalidare la cache
  • 9. IMemoryCache • Implementazione della cache InProc per ASP.NET Core • In ASP.NET Core 2 è già configurata di default • In ASP.NET Core 1 se ne deve specificare l'uso in fase di startup
  • 11. Tipologie di cache - distribuita Cache distribuita / Application cache • Redis • Memcached • SQL Server • … Utile in quanto può essere condivisa tra più applicativi, che possono anche risiedere su server differenti Il riavvio di un applicativo non causa la perdita dei dati in cache
  • 12. Redis "Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries." Database in-memory Diventato famoso per la sue performance in quanto a velocità di lettura/scrittura Offre la possibilità di poter persistere i dati https://redis.io/
  • 13. Chocolatey e redis • Installing Chocolatey • https://chocolatey.org/install Tramite powershell • > choco install redis-64 • > redis-server
  • 14. Redis client A seconda del client scelto • O fornisce metodi che lavorano con string o byte[] • O fa uso dei Generics in modo da poter deserializzare gli oggetti salvati e riportarli nel tipo corretto • Che internamente si occupa di gestire solo string o byte[] Per .NET Core esiste un client ufficiale Microsoft: • Microsoft.Extensions.Caching.Redis • Implementa IDistributedCache
  • 15. Memcached "Free & open source, high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load. Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering. Memcached is simple yet powerful. Its simple design promotes quick deployment, ease of development, and solves many problems facing large data caches. Its API is available for most popular languages." Supporta il salvataggio solo di stringhe (o oggetti serializzati) Lavora solamente in memoria https://memcached.org/
  • 16. Memcached client EnyimMemcached • https://github.com/enyim/EnyimMemcached • https://www.nuget.org/packages/EnyimMemcached/ Per .NETStandard 2.0 • https://www.nuget.org/packages/EnyimMemcachedCore
  • 18. Tipologie di cache - browser Gestione headers: • Cache-Control • Pragma • If-None-Match • Etag • If-Modified-Since • Age • … Varie tecnologie: • Output Cache • Response Cache • ETag Riduzione del numero di richieste verso l'applicativo Browser e/o proxy possono mantenere in cache una copia dell'output della richiesta
  • 19. Output cache Permette il controllo dell'header Cache-Control Permette di ridurre il numero di richieste verso il server Possibilità di inserire in cache l'output di una pagina aspx o di una chiamata ad un controller Si risparmia il tempo di generazione E' possibile parametrizzare la chiave con cui viene inserire l'elemento in cache, in modo che possa dipendere da vari fattori/parametri • Querystring • Utente • Form input • Lingua
  • 20. ResponseCache Implementata per ASP.NET Core in sostituzione dell'Output cache Permette il controllo dell'header Cache-Control Permette di ridurre il numero di richieste verso il server ResponseCache a differenza dell'Output cache non salva l'html di output ma gestisce solo l'header !! Non attivo se presente "antiforgery" !! Non attivo se header "authorization"
  • 21. Cache per i file statici E' possibile attivare lo stesso meccanismo del Response Cache anche per i file statici Si interviene manualmente nel metodo Configure della classe Startup.
  • 22. ETag Permette di risparmiare il tempo di traferimeto/download Si basa sul ritornare un hash del contenuto • Passato nell'header ETag Ritornare un 304 Not Modified nel caso di request con lo stesso hash (passato nell'header If-None- Match)
  • 23. DEMO Response cache e Static file
  • 24. Non è tutto oro quello che luccica La serializzazione si paga Il trasferimento dei dati si paga Invalidare correttamente i dati non è cosa semplice
  • 25. Serialization considerations • Protocol Buffers (also called protobuf) is a serialization format developed by Google for serializing structured data efficiently. It uses strongly-typed definition files to define message structures. • JSON is an open standard that uses human-readable text fields. It has broad cross-platform support. JSON does not use message schemas. • BSON is a binary serialization format that uses a structure similar to JSON. BSON was designed to be lightweight, easy to scan, and fast to serialize and deserialize, relative to JSON. Payloads are comparable in size to JSON. Depending on the data, a BSON payload may be smaller or larger than a JSON payload. BSON has some additional data types that are not available in JSON, notably BinData (for byte arrays) and Date. • MessagePack is a binary serialization format that is designed to be compact for transmission over the wire. There are no message schemas or message type checking. • …
  • 26. Links • Microsoft Best Practices - Caching • https://docs.microsoft.com/en-us/azure/architecture/best-practices/caching • Per ASP.NET Core: • In-memory caching • https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory • Distributed Cache • https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed • Cache Tag Helper • https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/cache-tag-helper • Distributed Cache Tag Helper • https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/distributed-cache-tag-helper • ResponseCache attribute • https://docs.microsoft.com/en-us/aspnet/core/performance/caching/response • ETag header in ASP.NET Core • https://madskristensen.net/blog/send-etag-headers-in-aspnet-core/
  • 27. Andrea Dottor Email: andrea@dottor.net Www: www.dottor.net Twitter: @dottor