Application of buffering technology to improve performance and stability of JSP application (3) Oschche

Source: Internet
Author: User

Oscache

Characteristics

Cache any object, you can cache portions of JSP pages or HTTP requests without restriction, and any Java object can be cached.

Having a comprehensive Api--oscache API gives you a comprehensive program to control all the Oscache features.

Persistent caching-caches can write to the hard disk at will, so it allows expensive creation (expensive-to-create) of data to keep the cache, even allowing the app to restart.

Support cluster--the cluster cache data can be configured by a single parameter without the need to modify the code.

Expiration of cached records-you can have maximum control over expiration of cached objects, including pluggable refresh policies (if default performance is not required).

Previous article on how to configure Oschche below describes how to apply:

1 Create a **bean cache class **cache.
2 Import Com.opensymphony.oscache.general.*;import com.opensymphony.oscache.base.*;
3 Create a **dao class to manipulate the database (you can also merge the contents of the last two items directly here).
4 generate an instance of Generalcacheadministrator in the **cache class admin is used to manage the cache.
Generalcacheadministrator admin = new Generalcacheadministrator ();
5 methods in **cache such as. Clear (), flush (). Basic calls to the Java API for Oscache.
6 Add the Getbeans () and Getbean () methods in **cache to get the instance objects in the cache. The implementation can refer to the example above.
7 The main methods of generalcacheadministrator used are
Public Object Getfromcache (String key) throws needsrefreshexception; --Gets the object identified by a key from the cache.
Public Object Getfromcache (String key, int refreshperiod) throws needsrefreshexception;  --Gets the object identified by a key from the cache. RefreshPeriod Refresh period, which identifies how long this object is saved in the cache (in seconds)

Attention:
If a needsrefreshexception appears, you must call Admin.putincache or admin.cancelupdate to avoid a deadlock condition.


There are 4 main types of Oscache used:
1.POJO Cache
2.HTTP Response Cache
3.JSP Tag Library Cache
4.O/R Data Access Cache

1. POJO Cache
This way the cache is directly called Oscache API, mainly for processing the page content will change dynamically according to the parameters, you can set the parameter to the key value to save the data:
First, declare the member variable:
Oscache Adminitrator Instance
private static Generalcacheadministrator cacheadmin = null;
Second, initialize:
Public Ringartistaction () {
Cacheadmin = new Generalcacheadministrator ();
}
To cache the Pojo:
Cache Data key and refresh period
String key = sex + ":" + place;
int refreshperiod = Constants.getintegervalue (constants.oscache_refresh_period). Intvalue ();
try {
Get from the cache
Artists = (MAP) cacheadmin.getfromcache (key, RefreshPeriod);
} catch (Needsrefreshexception nre) {
try {
Get the value (probably from the database)
int count = Getartistcount (sex, place, errors);
Artists = Getartistdata (Sex, place, count, errors);
Store in the cache
Cacheadmin.putincache (key, artists);
} catch (Exception ex) {
We have the current content if we want fail-over.
Artists = (MAP) nre.getcachecontent ();
It is essential this cancelupdate is called if the
Cached content is not rebuilt
Cacheadmin.cancelupdate (key);
Ex.printstacktrace ();
}
}
POJO (Simple Java object) cache. A Pojo cache is a system-it acts as an "object-oriented" distributed cache. In this system, once a user attaches pojo to the cache, the buffering aspects (such as replication and persistence) should be transparent to the user. A user simply needs to operate on the Pojo without worrying about updating the cached content or maintaining an object relationship. There is no explicit API call available to manage the cache.

2. HTTP Response Cache
This way the cache is used to handle the contents of the entire page fixed, not dynamically changed according to the parameters:
First configure the Cachefilter in Web. xml:
<filter>
<filter-name>CacheFilter</filter-name>
<filter-class>com.opensymphony.oscache.web.filter.CacheFilter</filter-class>
<init-param>
<param-name>time</param-name>
<param-value>86400</param-value>
</init-param>
<init-param>
<param-name>scope</param-name>
<param-value>application</param-value>
</init-param>
</filter>
Add all pages that need to be cached to filter-mapping:
<filter-mapping>
<filter-name>set Character encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Note that only content that returns a status of $ (HTTPSERVLETRESPONSE.SC_OK) will be cached

The purpose of caching in HTTP is to reduce sending requests in many cases, and to return the cache directly, and in many cases it is not necessary to send a full response. The former reduces the number of network loops, is very high response speed, HTTP uses an "expiration (expiration)" mechanism to this end. The latter reduces bandwidth for network applications, and HTTP uses the "Authentication (validation)" mechanism for this purpose.

HTTP defines 3 kinds of caching mechanisms:

L freshness allows a response to being used without re-checking it on the origin server, and can be controlled by both the SE RVer and the client. For example, the Expires response header gives a date when the document becomes stale, and the cache-control:max-age dire Ctive tells the cache how many seconds the response was fresh for.

L Validation can used to check whether a cached response are still good after it becomes stale. For example, if the response have a last-modified header, a cache can make a conditional request using the If-modified-sinc E header to the if it has changed.

L invalidation is usually a side effect of another request that passes through the cache. For example, if URL associated with a cached response subsequently gets a POST, PUT or DELETE request, the cached response would be invalidated.

How HTTP Response caching works

All caches use a set of rules to help them decide when to use a copy of the cache to provide services (assuming a copy is available); some rules are defined in the Protocol (HTTP protocols 1.0 and 1.1), and some rules are set by the cache administrator (the browser's user or the administrator of the proxy server);
Generally: follow these basic rules (don't worry, you don't have to know all the details, the details will be explained later)
1. If the response header information: Tell the cache not to preserve the cache, the cache will not cache the corresponding content;
2. If the request information is required authentication or security encryption, the corresponding content will not be cached;
3. If the validator (ETag or last-modified header information) does not exist in the response, the cache server considers that there is a lack of direct update information and that the content will be considered non-cacheable.
4. If a cached copy contains the following information: Will the content be considered new enough? Contains the complete expiration time and the life Control head information, and the content is still in the freshness period;
The browser has used cached copies and has checked the freshness of the content in a single session;
The cache proxy Server has used cached copies in the near future, and the last update time for the content is before the last use period;
? A new copy will be sent directly from the cache without sending a request to the source server;

5. If the cached copy is already too old, the cache server will issue a request validation request to the source server to determine whether the service can continue to continue using the current copy;

In summary: Freshness and validation are the most important ways to determine if content is available:

If the copy is new enough, it can be used immediately if it is extracted from the cache;
After the buffer check, the original copy is not changed, the system will also avoid the copy content from the source server the entire retransmission again.


3. JSP Tag Cache
The JSP tag cache is primarily used to cache the local content of a JSP page:
<cache:cache key= "Especialcategory" cron= "* 5 * * *" >
<jsp:include page= "/ringcategory.do" flush= "true" >
<jsp:param name= "Ringtype" value= "1"/>
</jsp:include>
</cache:cache>

Page caching is usually implemented using Oscache, Oscache provides a JSP tag that can be used to contain the content part that needs to be cached, of course, the content part of the cache needs to have the server request or logical calculation, imagine, There is no point in caching a static HTML. The use of the page cache for the system does have a significant increase in response speed, in the implementation of the page cache is the most troublesome is the definition of the cache key and the notification of cache updates, this natural framework can not be resolved, but the notification of the cache update the real framework may consider a notification model, like event notification. In a real project, you can implement a notification model or simply use a single example to identify if a key needs to be updated.

A few suggestions for JSP cache
1.jsp Cache is best done on the filter, the need to buffer the page in the same directory, each change only need to change the Web. XML to complete the buffer settings, it is more convenient.
2.Gzip compression can compress the page very small, the average compression ratio for the 1/3,jsp cache HashMap buffer compressed pages, is certainly more than uncompressed before the memory consumption, and more efficient.


4. O/R Data Access Cache

Data cache estimates are familiar, that is, the way the system data is cached, typically hibernate's first-level, two-level data cache.
Data caching in implementation if you are using Hibernate, it is more direct to use Hibernate's first level, level two and query cache, if you want to implement it, you can refer to the implementation mechanism of hibernate.
The data cache key is used in the first level, level two cache is the value of the identity key of the data, the query cache is the query parameters, query the way the statement.
The update of the data cache is that hibernate updates the contents of the cache directly while it is being stored, and the query cache is all directly purged, so that it will naturally be queried again the next time the query is made.
You may wonder why the page cache and processing cache do not use this way to implement the cache updates, a little bit to know, in the background when the change is not really know what key to remove,
So hibernate in order to avoid this trouble, the use is when the data changes once the full query cache is cleared, rather than just to clear the relevant cache,
In fact, there can be a subscription-based model, of course, it also increases the complexity of the framework.

The most powerful of the ORM cache is its transparency and flexibility to configure, you can use Ehcache, you can choose JBoss, you can also use Tangosol.

Please read the contents of the resources for more information.

Resources:
Taking the load Off:oscache helps databases cope:http://www.theserverside.com/articles/article.tss?l= Oscachehelpsdatabases


Specific implementation:

Building the cache management class CacheManager
Package com.jrgy.util;
public class CacheManager {
Private Basecache Newscache;
private static CacheManager instance;
private static Object lock = new Object ();


Private CacheManager () {
Initial basecache;
Newscache = new Basecache ("Cnyjweb", 12000);
}

public static CacheManager getinstance () {
if (instance = = null) {
Synchronized (lock) {
if (instance = = null) {
Instance = new CacheManager ();
}
}
}
return instance;
}

Delete? All cached objects
public void Removeallcache () {
Newscache.removeall ();
}

To delete a cached object
public void Delcachebykey (String key) {
Newscache.remove (key);
}

To add a cached object
public void Add (String key, Object value) {
Newscache.put (key, value);
}

Gets the object being cached
Public Object get (String key) {
try {
return Newscache.get (key);
} catch (Exception e) {
return null;
}
}

}


The establishment of a tool class Basecontroller Generalcacheadministrator is mainly related to the preservation and removal of persisted objects.

Package com.jrgy.util;
Import Java.util.Date;
Import com.opensymphony.oscache.base.NeedsRefreshException;
Import Com.opensymphony.oscache.general.GeneralCacheAdministrator;

public class Basecache extends Generalcacheadministrator {

Private static final long serialversionuid = -4397192926052141162l;

private int refreshperiod; Expiration time (in seconds);

Private String Keyprefix; Before the keyword?? Characters


Public Basecache (String keyprefix, int refreshperiod) {
Super ();
This.keyprefix = Keyprefix;
This.refreshperiod = RefreshPeriod;
}

Add the cached object;
public void put (String key, Object value) {
This.putincache (This.keyprefix + "_" + key, value);
}

Delete the cached object;
public void Remove (String key) {
This.flushentry (This.keyprefix + "_" + key);
}

Delete by date? cached pairs of objects;
public void RemoveAll (date date) {
This.flushall (date);
}

Delete all the cached objects?;
public void RemoveAll () {
This.flushall ();
}

Gets the object being cached;
Public Object get (String key) throws Exception {
try {
Return This.getfromcache (This.keyprefix + "_" + key,
This.refreshperiod);
} catch (Needsrefreshexception e) {
This.cancelupdate (This.keyprefix + "_" + key);
Throw e;
}
}
}

Using Oschache

Package Com.jrgy.web.controller;

Import java.io.UnsupportedEncodingException;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;

Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import Net.sf.json.JSONArray;

Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.servlet.ModelAndView;

Import Com.jrgy.main.service.impl.LoadStartDataManagerImpl;
Import Com.jrgy.pojo.domain.DocInfo;
Import Com.jrgy.pojo.domain.FriendlyLink;
Import Com.jrgy.pojo.domain.ItemInfo;
Import com.jrgy.pojo.domain.Periodical;
Import com.jrgy.util.Constants;
Import com.jrgy.util.ItemCodeConstants;
Import Com.jrgy.util.PageObject;
Import Com.jrgy.util.PageView;
Import Com.jrgy.web.service.IWebIndexManager;

@Controller
public class Webindexcontroller extends Basecontroller {

Private static final long serialversionuid = 6316819588600885728L;
@Autowired
Iwebindexmanager Webindexmanager;

@Autowired
Loadstartdatamanagerimpl Loadstartdata;
@SuppressWarnings ("Unchecked")
@RequestMapping ("/index.do")
Public Modelandview savedept (HttpServletRequest request,
HttpServletResponse response) {
PageObject pageobject = new PageObject ();
list<iteminfo> itemList = new arraylist<iteminfo> ();//Get column

if (itemList = (list<iteminfo>) getcache (itemList, Itemcodeconstants.cache_jrgy_item)). Size () = = 0) {
ItemList = Webindexmanager.additemlist (Itmecode);
Addcache (Itemcodeconstants.cache_jrgy_item, itemList);
}


}
}

Because you configure the folder to generate the cache in D:\CNYJWeb\cache\application:


Conclusion:
1. The cache is emptied and updated so as to be as precise as possible to manipulate the objects affected by the update, not all of them.
In Hibernate, it also provides a fine-grained way to empty cache objects, such as Sessionfactory.evict (class, id).
Sessionfactory.evice (Class) operations, to see if such operations are frequent, if frequent, the role of the cache will be greatly discounted.
2. If the cache object is too large, for the algorithm and processing of the failure, and the characteristics of the business object tightly together, through the event to drive the failure of the object.
3. For the caching of Business objects, the life cycle and business characteristics of objects must be deeply analyzed.
4. There should be sufficient awareness and prevention tools for the risk of inconsistent data.
5. Reasonably estimate the size of the object and allocate enough memory
6. If you only use the central cache, only to reduce the pressure of the database, the pressure on the network bandwidth, or some, the speed is far less than the effect of local cache, so to combine the local cache + central cache policy scheme, that is, to improve speed, avoid cluster replication bottlenecks.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.