פתרונות caching במערכות WEB

מאת item-soft
בתאריך 9 ינואר, 2013

מהירות טעינת הדפים באפליקציית WEB חשובה מאוד כדי להעצים את חווית המשתמש ובעיקר כדי להגביר את התגובתיות של האתר ולאפשר עבודה רציפה בלי שהמשתמש יצטרך לחכות בזמן שהשרת "חושב".

פתרונות caching במערכות WEB

 

מה עושים אם אחרי ששיפרנו את יעילות הקוד, את השאילתות, הוספנו אינדקסים וחסכנו בלולאות מהירות התגובה עדיין לא משביעה רצון?

 

Cacheהוא הפתרון!

 

מה שהיה פעם מסובך, הפך עכשיו למאוד פשוט.

נניח שיש דף באפליקציה שמציג נתונים שנשמרו בבסיס הנתונים, והשאילתה שמאחזרת את הנתונים היא "כבדה". לא נרצה שבכל פעם שמשתמש יבקש את הדף הזה, השרת יריץ את השאילתה ויביא שוב את הנתונים. אפשר לנצל את הפעם הראשונה שהשרת הביא את הנתונים כדי "לשמור" את התוצאה ובפעם הבאה שמשתמש יבקש את אותו הדף, הוא כבר יהיה מוכן.

שמירה של דף שלם ב Cacheנקרא Output Cache.

 

כל מה שצריך כדי להגדיר Output Cacheלדף מסוים הוא להוסיף את ההצהרה הבאה בראש העמוד:

<%@OutputCache Duration="60" VaryByParam="None"%>                            

 

הפרמטר הראשון, Duration, הוא הזמן בשניות שבו השרת מחזיק את הגרסה של הדף. בקשה לדף אחרי פרק הזמן הזה תגרום לשרת "לחשב" שוב את הדף.

 

הפרמטר השני, VaryByParam, מאפשר גמישות גדולה מאוד באשר להגדרת הגירסה של הדף שנשמר. נניח שהדף בדוגמה הנ"ל הוא דף שמציג תוצאות חיפוש. מן הסתם, הפרמטר לחיפוש עובר לשרת ב POSTאו GET. אם נתעלם מהפרמטר שעובר, כל חיפוש (אחרי החיפוש הראשון) יחזיר את אותו דף שנשמר ב Cache. אם נתחשב גם במשתנה החיפוש, אז כל ערך שונה בחיפוש יישמר כדף נפרד ב Cache.

 

אם יש בדף TextBoxשמכיל את משתנה החיפוש, למשל:

<asp:TextBoxID="SearchParam" runat="server"></asp:TextBox>

 

אז כדי "להתחשב" במשתנה החיפוש יש לכלול את ה IDשל ה TextBoxב VaryByParam:

<%@OutputCache Duration="60" VaryByParam="SearchParam"%>

 

במידה ויש יותר ממשתנה אחד שרוצים לקחת בחשבון, אפשר להפריד ביניהם בנקודה-פסיק (;).

 

 

אפשרות אחרת לשימוש ב Cacheהיא שמירה של נתונים ספציפיים בתוך הדף – Data Cache.

אפשר לחשוב על מקרה שבו, בדפים שונים באפליקציה, יש "קופסא" שמציגה את אותם הנתונים, או תפריט שמיוצר באופן דינאמי אבל הוא זהה בכל הדפים ועבור כל המשתמשים. אין סיבה שהשרת יעבוד קשה כדי להביא בדיוק את אותם הנתונים בכל פעם. ניתן להגדיר משתנים שנשמרים ברמת ה Cacheוהם זמינים בכל האתר. בפעם הראשונה שהשרת יתבקש להביא את הנתונים הוא יבדוק אם הם כבר קיימים ב Cache. כמובן שהתשובה היא לא (כי זו הפעם הראשונה) ולכן הוא יביא וישמור אותם. בפעם הבאה שהוא יתבקש להביא אותם הוא יבדוק אם הם קיימים, והפעם התשובה חיובית. הוא ייקח אותם מה Cacheויחסוך את החישוב.

DataTableResultSet = new DataTable();

if(Cache["ResultSetData"] == null)

{

    ResultSet = SomeMethodThatReturnData();

}

else

{

    ResultSet = (DataTable)Cache["ResultSetData"];

}

 

 

 

 

 

 

 

 

 

 

Caching solutions in WEB

 

 

Page load speed WEB app very important to enhance the user experience and especially to increase the responsiveness of the site and to enable continuous work without the user having to wait while the server "thinks".

What do you do if after approving the code efficiency, the queries, we have added indexes and saved loops speed of response is still not satisfied?

 

 

Cache  is the solution !

 

 

What was oncedifficult, nowbecomeextremelysimple.
Suppose thatapplicationpagethat displaysdatastoredin the database, andqueryretrieves the datais"heavy".

We would not likethat every timea userrequests thepage,the serverwill run thequeryand bringbackthe data.

You canuse thefirst timethat the serverbrought thedatato "save"hisresultandnext time that userrequests thesame page, hewas ready.
Savethewhole pageincalledOutputCacheCache.

All you needto setOutputCacheto a particular pageis to addthe following statementat the top ofthe page:

 

 

<%@OutputCache Duration="60" VaryByParam="None"%>                            

 

 

 

 

The first parameter, Duration, is time in seconds that the server holds the version of the page. Page request after this time will serve "calculate" over the top.

The second parameter, VaryByParam, great flexibility in defining the version of the page is saved.

Suppose the page in the example above is a page that displays search results.

Probably going to serve search parameter in POST or GET. If we ignore the before parameter passing, all the search (after the first search) returns the same page saved in Cache.

If the variable search allowances, So all the different value is saved as a separate search in Cache.

If a page contains a TextBox containing the search variable, for example:

 

<asp:TextBoxID="SearchParam" runat="server"></asp:TextBox>

 

 

Soto"consider" the searchvariablemust includetheIDoftheTextBoxinVaryByParam:

 

<%@OutputCache Duration="60" VaryByParam="SearchParam"%>

 

 

 

Should there bemorethan one variableyou wantto take into consideration, can beseparatedat the point-semicolon (;).


Another optionfor usingtheCacheiskeepingspecific datawithin the page- DataCache.
You can think ofa case in which, on different pagesapplication, there is a "box" that displays thesame data, ordynamicallyproducedmenubutis the sameon all pagesandfor all users. There is no reasonthat the serverwill work hardtogetexactlythesame dataeach time.

You can definethevariablesthat are keptlevelCacheand are availablethroughout the site. For the first timethat the serverwill be asked tobringthe dataisto checkiftheyalready existin theCache.

Of coursethe answer is no(forthe first time) andsohewill bringand keepthem. Next timehewill be asked tobringthemhewould see ifthey exist, and this timethe answer is yes.

Hewill takethem towhatCacheandsavethecalculation.

 

DataTableResultSet = new DataTable();

if(Cache["ResultSetData"] == null)

{

    ResultSet = SomeMethodThatReturnData();

}

else

{

    ResultSet = (DataTable)Cache["ResultSetData"];

}

מאמרים נוספים...