aspnet caching

30
http://www.linkedin.com/in/thisisshubho

Upload: rainynovember12

Post on 02-Nov-2014

4.179 views

Category:

Documents


3 download

DESCRIPTION

An Introduction to caching in Asp.net

TRANSCRIPT

Page 1: Aspnet Caching

http://www.linkedin.com/in/thisisshubho

Page 2: Aspnet Caching

Overview

Introduction to ASP.NET caching Output caching Fragment caching Data caching

2

Page 3: Aspnet Caching

Introduction to Caching in ASP.NET Caching is the most critical factor in creating

scalable, high performance Web applications Caching locations

Web server, proxy server, and client browsers Types of caching

Output cachingFragment cachingData caching

3

Page 4: Aspnet Caching

Output Caching

What is output caching? @ OutputCache directive and the cache object Output caching attributes:

DurationLocationVaryByParamVaryByHeaderVaryByCustom

4

Page 5: Aspnet Caching

What Is Output Caching?

Pages that use the output cache are executed one time, and the page results are cached

The pre-executed page is then served to later requests

Performance and scalability both benefitServer response times reducedCPU load reduced

Appropriate caching of pages affects site performance dramatically

5

Page 6: Aspnet Caching

@ OutputCache Directive and the Cache Object

@ OutputCache declaratively controls caching behaviorFor .aspx, .asmx, or .ascx

The cache object programmatically controls caching behavior

6

<%@ OutputCache Duration="600“ Location="Any“VaryByParm=“none” %>

Is equivalent to:[C#]Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));Response.Cache.SetCacheability(HttpCacheability.Public);

Page 7: Aspnet Caching

OutputCache Members: Duration and Location

Duration sets the time to cache the output In seconds Required

Location sets the location to cache the output Server: The output is held in memory on the Web server and is

used to satisfy requests Downstream: A header is added to the response to indicate to

proxy servers to cache the page Client: A header is added to the response indicating to browsers

to cache the page Any: Output cache can be located on any of these locations None: No output caching is turned on for the item

7

<%@ OutputCache Duration="600" Location="Any“VaryByParam=“none” %>

Page 8: Aspnet Caching

OutputCache Members: VaryByParam and VaryByHeader

VaryByParam The cache stores multiple copies of a page based on specific

Querystring or Form parameters and any combinations thereof

VaryByHeader The cache stores multiple copies of a page based on HTTP

headers

8

<%@ OutputCache Duration="10“ VaryByParam="location;count" %>

<%@ OutputCache Duration="60“ VaryByHeader="Accept-Language" %>

Page 9: Aspnet Caching

OutputCache Members: VaryByCustom

VaryByCustom If the value is “Browser,” cache varies by browser type and major

version If the value is a custom string, you must override

HttpApplication.GetVaryByCustomString in the Global.asax and implement your own caching logic

9

Page 10: Aspnet Caching

Fragment Caching

What is fragment caching? VaryByControl Nested cached user controls Cached controls are not programmable

10

Page 11: Aspnet Caching

What Is Fragment Caching? Just as you can vary the versions of a page that

are output cached, you can output cache regions of a page

Regions are defined based on user controls User controls contain their own @OutputCache

directive Fragment caching supports

VaryByParamVaryByControl

Location not supported because fragments must reside on server to be assembled

11

Page 12: Aspnet Caching

Fragment Caching a User Control[*.ascx][*.ascx]<%@ Language="C#" %> <%@ Language="C#" %> <%@ OutputCache Duration="10“ <%@ OutputCache Duration="10“

VaryByControl="State;Country" VaryByControl="State;Country" VaryByParam="*"%> VaryByParam="*"%> <script runat=server> <script runat=server> public String State { public String State { get { return state.Value; } get { return state.Value; } set { state.Value = State; } } set { state.Value = State; } }

public String Country { public String Country { get { return country.Value; } get { return country.Value; } set { country.Value = Country; } } set { country.Value = Country; } } </script></script>

12

Page 13: Aspnet Caching

VaryByControl

VaryByControlThe sixth attribute supported by OutputCacheOnly supported in user control cachingCaching is based on user control properties

13

<%@ OutputCache Duration="10“ VaryByControl="State;Country“ VaryByParam="*"%>

Page 14: Aspnet Caching

Post cache substitution

Allows to substitute (Replace/modify) a (Small) portion of a cached page output

Very useful to use where little content in the rendered page varies depending on parameter(s)

Use an asp:substitution to implement the Post cache substitute

Provide a method for the call back, that renders the markup for the substitution.

14

Page 15: Aspnet Caching

SQL dependency

Output Caching/ Fragment caching could be configured to use SQL dependency so that, cached Page/User control will be updated when corresponding table(s) data is/are updated

SQL dependency is usable in Both SQL server 2000 and SQL server 2005

15

Page 16: Aspnet Caching

SQL dependency The “Polling model” has to be used in SQL

server 2000 to use Cache dependency--Application “Polls” data after a given period of time--Requires more effort in configuring--More resource intensive

The “Notification model” can be used in SQL server 2005 to use Cache dependency--Requires less effort in configuring--DB server “Notifies” application with Updates--Less resource intensive

16

Page 17: Aspnet Caching

SQL dependency:Example In ASPX, or, ASCX page, use

<asp:SqlDataSource EnableCaching="True" SqlCacheDependency="Northwind:Products" ... />

In web.config, use the following configuration:<caching>

<sqlCacheDependency enabled="true“ pollTime="1000"> <databases> <add name="Northwind“

connectionStringName="NorthwindConnectionString1"/> </databases> </sqlCacheDependency> </caching> Enable SQL server for SQL dependency: Execute following command in the

command prompt aspnet_regsql.exe -S %Server% -U %uid% -P %pwd% -d %Database% -t %TableName%

-et

17

Page 18: Aspnet Caching

Page/Fragment output cache : Best practices

Don’ts Generally use of output cache in pages that contain input

forms is not a good idea. Generally, it is good practice to not to use output caching

in pages that requires authentication. Don’t use output cache for static page. Don’t use output cache for page that contains lighter

content Don’t use output cache for page that generally executes

faster

18

Page 19: Aspnet Caching

Page/Fragment output cache : Best practices

Do’s Use output cache in public pages Use output cache for pages that executes slower Use output cache for pages that contains heavy

contents Use output cache for pages that are frequently

being accessed. Use Fragment cache (Output cache at User

controls) to cache varying common dynamic contents across the pages

19

Page 20: Aspnet Caching

Page/Fragment output cache : Best practices

Do’s Use Post cache substitution for fewer contents

in the pages that vary across different parameters

Use SQL dependency (With longer durations) with output cache for pages that uses data that are very frequently accessed, expensive to retrieve and that are not changed often.

Set smaller durations for output cache in pages that varies too much depending on input parameters, and/or, that are not frequently accessed

20

Page 21: Aspnet Caching

Page/Fragment output cache : Best practices

Do’s Use moderate duration for pages that are less

frequently accessed and/or that doesn’t vary too much with input parameters

Use long duration for pages that are very frequently accessed and/or that vary little with input parameters

Use Output cache profiles for better manageability (Configuring profiles in web.config)

21

Page 22: Aspnet Caching

Data Caching

What is data caching? Working with the cache object Cache dependencies Scavenging memory Using callbacks with caching

22

Page 23: Aspnet Caching

What Is Data Caching?

The data cache holds application data such as strings, datasets, and other objects

Adding items to the data cache is easy

Although similar to the familiar application variables model, it is much more powerful

23

Cache [“counter”] = mycount.text

Application[“counter”] = mycount.text

Page 24: Aspnet Caching

Working with the Cache Object Cache object features

Dependencies allow logic to invalidate cached itemsScavenging (automatic expiration)Callbacks when an item is removed from cache

To use dependencies or callbacks, use Cache.Insert or Cache.Add

Code using cached items must be able to both create or insert, and retrieve cached items

24

Public DataSet GetProductData(){ if (Cache["ProductData“] = null) { Cache["ProductData“] = LoadDataSet(); }  Return Cache["ProductData“];}

Page 25: Aspnet Caching

Cache Dependencies File-based dependencies

Cached item invalidated when files change Key-based dependencies

Cached item invalided when another cached item changes

Time-based dependenciesAbsolute time-based invalidationsSliding time-based invalidations

SQL dependenciesSQL based invalidations

25

Page 26: Aspnet Caching

Scavenging Memory

Automatic system that initiates when memory becomes scarce

Tag cached items with relative importanceCacheItemPriority CacheItemPriorityDecay

Items must be added to cache using .Add or .Insert to make use of these enumerations

26

Page 27: Aspnet Caching

Using Callbacks with Caching Create Callbacks with this delegate:

CacheItemRemovedCallback Callbacks are used to receive notification when

an item is evicted from the cacheCleanupUpdateRecreateLogging

Items must be added to caching using .Add or .Insert to use callback functionality

27

Page 28: Aspnet Caching

Caching in Web Farm

ASP.NET cache is not usable in a web farm scenario (Load-balanced distributed deployment).

The .NET remoting could be used to develop a cache server, or, third party caching provider can be used (Ncache, Distributed Cache etc)

28

Page 29: Aspnet Caching

Review

Code that uses items from the data cache must be able to create the object, load the cache, or retrieve the object before using it.

Caching can hide problems. Test without caching. Use tracing, performance counters, and stress

software to identify caching wins.

29

Page 30: Aspnet Caching

More information

aspnet.4guysfromrolla.com/articles/022802-1.aspx

msdn.microsoft.com/en-us/library/ms972362.aspx

30