Simple and practical ehcache + spring

Source: Internet
Author: User

1. Recently, a loan project is a sub-station in the city divided into a loan front-end and a loan institution back-end. The two platforms have different second-level domain names, and one front-end is cityname.xx.com, cityname varies by region. For example, in Beijing, it is bj.xx.com, and in the backend is loan.xx.com. When you log on to an institution, if you put the login information in session, there will be a problem, that is, when you switch to the front-end, because the domain name changes, the session will change, and the information stored in the previous session will not exist, that is, the session cross-domain problem, finally, I thought of using the cache to store online user information, so that there is no cross-domain session issue.

2. Introduction to ehcache

Ehcache is a pure Java in-process cache framework, which features fast and efficient. It is the default cacheprovider in hibernate.

Is the location of ehcache in the application:

Main features include:

1. Fast.
2. Simple.
3. Multiple cache policies
4. There are two levels of cache data: memory and disk, so there is no need to worry about capacity issues
5. the cached data will be written to the disk during the VM restart process.
6. distributed cache can be implemented through RMI, pluggable API, and other methods
7. Listening interfaces with cache and cache manager
8. Supports multiple cache manager instances and multiple cache regions of one instance
9. Provides hibernate cache implementation

The following describes how to use ehcache.

① Download ehcache. jar and go to Google

② Then, configure the ehcache attributes. ehcache requires an XML file to set attributes related to ehcache, such as the Maximum Cache quantity and cache refresh time.

Put ehcache. xml under your classpath.

<Ehcache> <! -- <Diskstore Path = "C: \ MyApp \ cache "/> --> <defaultcache maxelementsinmemory =" 1000 "Eternal =" false "timetoidleseconds =" 120 "timetoliveseconds =" 120 "overflowtodisk =" false "/> <cache name = "default_cache" maxelementsinmemory = "10000" Eternal = "false" timetoidleseconds = "300000" timetoliveseconds = "600000" overflowtodisk = "false"/> </ehcache> <! -- 1. Required attribute: Name: the name of the cache, which is used to identify different caches and must be unique. Maxelementsinmemory: Maximum number of cache elements in memory management. Maxelementsondisk: Maximum number of cache elements managed by a hard disk. The default value is 0, which means there is no limit. Eternal: Specifies whether the element is persistent. If it is set to true, the cached element will not expire. Overflowtodisk: determines whether to transfer data to the disk when the memory is full. 2. The following are optional attributes: timetoidleseconds: Set the idle time of the element before expiration, which is only valid for non-persistent cache objects. The default value is 0, and the value is 0, which means that the element can be idle for an unlimited period of time. Timetoliveseconds: specifies the time from creation to expiration of an element. Similar to timetoidleseconds. Diskpersistent: Specifies whether to store disks when the VM is restarted. The default value is false. (In my intuition, it is recommended to set this value to true for secure small applications ). Diskexpirythreadintervalseconds: the time when the disk thread is accessed. Diskspoolbuffersizemb: the buffer size when the disk is stored. The default value is 30 mb. Each cache has its own buffer. Memorystoreevictionpolicy: cache rule for element eviction. There are three types, which are least recently used by recently used (LRU) and default. First in first out (FIFO), first in first out. Less frequently used (specified as LFU) least->

③ Use the spring3 Interceptor to check whether the cache contains user information

Package COM. woaika. loan. front. common. filter; import javax. annotation. resource; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import javax. servlet. HTTP. httpsession; import net. SF. ehcache. cache; import net. SF. ehcache. element; import Org. apache. log4j. logger; import Org. springframework. web. servlet. handlerinterceptor; import Org. springframework. web. servlet. modelandv Iew; import COM. woaika. loan. front. loanuser. VO. loginorganvo; import COM. woaika. loan. IP. iputil; import COM. woaika. loan. po. loanorgan; public class orgmgtinterceptor implements handlerinterceptor {private logger log = logger. getlogger (orgmgtinterceptor. class); Private cache ehcache; @ Resource (name = "ehcache") Public void setehcache (Cache ehcache) {This. ehcache = ehcache;} public void aftercompletion (httpservle Trequest arg0, httpservletresponse arg1, object arg2, exception arg3) throws exception {// log.info ("================ execution order: 3. aftercompletion ==================== ");} public void posthandle (httpservletrequest arg0, httpservletresponse arg1, object arg2, modelandview arg3) throws exception {// log.info ("================= execution order: 2. posthandle ====================== ");} public Boolean prehandle (httpservletrequest request, htT Pservletresponse response, Object Handler) throws exception {// log.info ("================= execution order: 1. prehandle ====================== "); string IP = iputil. getremortip (request); element elementip = ehcache. get (IP); If (null = elementip) {response. sendredirect (COM. woaika. loan. commons. constants. siteconstant. jigou_url + "/tologin"); Return false;} else {loginorganvo = (loginorganvo) elementip. getobjectvalue (); If (VO! = NULL) {element elementid = ehcache. Get (VO. GETID (). tostring (); If (elementid! = NULL) {string tempip = (string) elementid. getobjectvalue (); If (tempip! = NULL &&! "". Equals (tempip) & IP. equals (tempip) {request. setattribute ("currentorgan", VO); Return true ;}} else {response. sendredirect (COM. woaika. loan. commons. constants. siteconstant. jigou_url + "/tologin"); Return false ;}} return true;/* string url = request. getrequesturl (). tostring (); // If (URL. matches (mappingurl) {httpsession session = request. getsession (); loanorgan org = (loanorgan) session. getattribu Te ("currentorgan"); If (Org! = NULL) {return true;} else {response. sendredirect (COM. woaika. loan. commons. constants. siteconstant. jigou_url + "/tologin");} return false; //} // return true ;*/}}

④ Configuration applicationContext-ehCache.xml for injecting ehcache

<Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: context = "http://www.springframework.org/schema/context" xmlns: P = "http://www.springframework.org/schema/p" xmlns: MVC = "http://www.springframework.org/schema/mvc" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: AOP = "http://www.springframework.org/schema/aop" xmlns: Tx = "http://www.springframework.org/schema/tx" xsi: schemalocati On = "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop /Spring-aop-3.0.xsdhttp: // www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "> <! -- Reference ehcache configuration --> <bean id = "defaultcachemanager" class = "org. springframework. cache. ehcache. ehcachemanagerfactorybean "> <property name =" configlocation "> <value> classpath: ehcache. XML </value> </property> </bean> <! -- Define the ehcache factory and set the cache name used --> <bean id = "ehcache" class = "org. springframework. cache. ehcache. ehcachefactorybean "> <property name =" cachemanager "> <ref local =" defaultcachemanager "/> </property> <property name =" cachename "> <value> default_cache </value> </property> </bean> </beans>

⑤ When logging on, verify the username and password and put it in the cache correctly. Here is a simple method (using spring MVC)

@ Requestmapping (value = "/login") Public String login (string organname, string PWD, httpservletrequest request, httpservletresponse response) {judgmentcity. getcityinfo (request); loanorgan organ = loanorganservice. login (organname, PWD); If (Organ = NULL) {request. setattribute ("MSG", "incorrect user name or password"); Return "Forward:/jigou/tologin";} else {// save the Organization information to the cache, cross-origin string IP = iputil. getremortip (request); loginorganvo Vo = new loginorganvo (); vo. setid (organ. GETID (); vo. setorganname (organ. getorganname (); element elementip = new element (IP, (serializable) VO); element elementid = new element (organ. GETID (). tostring (), ip); // element elementvo = new element (organ. GETID (). tostring (), (serializable) VO); ehcache. put (elementip); // Add to cache ehcache. put (elementid); // ehcache. put (elementvo); // request. getsession (). setattribute ("currentorgan", organ); Return "Redirect:/organmgt/Index ";}}

Logout operation (using spring MVC ):

// Log out and log out @ requestmapping (value = "/logout") Public String logout (httpservletrequest request) {string IP = iputil. getremortip (request); element elementip = ehcache. get (IP); If (elementip! = NULL) {loginorganvo Vo = (loginorganvo) elementip. getobjectvalue (); If (vo! = NULL) {ehcache. remove (vo. GETID () ;}} ehcache. remove (IP); // request. getsession (). removeattribute ("currentorgan"); Return "Redirect:/jigou/tologin ";}

⑥ Spring3 interceptor configuration file

<MVC: interceptors> <MVC: Interceptor> <MVC: Mapping Path = "/organmgt/**"/> <! -- If not configured or/*, All controllers will be blocked --> <Bean class = "com. woaika. loan. front. common. filter. orgmgtinterceptor "> </bean> </MVC: Interceptor> </MVC: interceptors>

In this way, all the requests starting with/organmgt/will be blocked, and you can check whether the interceptor is logged on, here, I use the user Client IP address and user ID to store the user information to ensure that the user's unique message.

In fact, a simple spring + ehcache framework is basically complete.

I have not mentioned much about Spring IoC and annotation-based injection here. I would like to Google many of them. mvc I use spring MVC, and there are also a lot on the Internet. I will know it on Google.

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.