Practical scenarios for Java cache classes

Source: Internet
Author: User

Don't be obsessed with technology, focus on the problem.

  A common background management system, there will be parameter configuration. Parameter Configuration data table and other data table is different, its operation is basically a check operation. Parameter configuration of this data information is throughout the project, then put them where can be convenient class or JSP call?

Spring's configuration file has a supported cache class, which is configured as follows:

 <!--Enable user's caching feature -      <BeanID= "Usercache"class= "Org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache">          < Propertyname= "Cache"ref= "Userehcache" />      </Bean>      <BeanID= "Userehcache"class= "Org.springframework.cache.ehcache.EhCacheFactoryBean">          < Propertyname= "CacheName"value= "Usercache" />          < Propertyname= "CacheManager"ref= "Ehcachemanager" />      </Bean>    <BeanID= "CacheManager"class= "Org.springframework.cache.ehcache.EhCacheCacheManager"P:cache-manager-ref= "Ehcachemanager"/>    <BeanID= "Ehcachemanager"class= "Org.springframework.cache.ehcache.EhCacheManagerFactoryBean"p:config-location= "Classpath:config/ehcache.xml"/>

  

Then add the appropriate annotations to our own cache class:

 PackageCn.wangze.service;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.cache.annotation.CacheEvict;Importorg.springframework.cache.annotation.Cacheable;ImportOrg.springframework.stereotype.Service;ImportCn.wangze.domain.SysMenu;ImportCn.wangze.domain.SysParam;Importcn.wangze.utils.AuthUtils; @Service Public classsyscacheservice{//data that needs to be cached depends on your business    /*** The menu data in the project is rarely changed, so we put the menu data in the cache **/@AutowiredPrivateSysmenuservice<sysmenu>Sysmenuservice; /*** Service that injects system parameters **/@AutowiredPrivateSysparamservice<sysparam>Sysparamservice; /*** Create map object to save data of system parameters, convenient to call*/    PrivateMap<string,string>Sysparammap; /*** By calling this method you can fetch the cached menu data*/@Cacheable (Value= "Syscache", key= "MethodName")     PublicList<sysmenu>querymenulist () {List<SysMenu> list =sysmenuservice.querylist (); if(List = =NULL|| List.size () = = 0)return NULL;        Authutils.clear ();  for(intI=0;i<list.size (); i++) {Sysmenu m=List.get (i);        Authutils.addauth (M.getid (), M.geturl ()); }        returnlist; }        /*** Clear some data from the cache and empty if the parameter type is querysysparamlist **/@CacheEvict (Value= "Syscache", key= "#p0")     Public voidremovecatch (String type) {if(Type.equals ("Querysysparamlist")){             This. Sysparammap =NULL; }    }        /*** Clear all data in the cache **/@CacheEvict (Value= "Syscache", allentries=true)     Public voidRemoveAll () { This. Sysparammap =NULL; }        /*** View all data in cache **/@Cacheable (Value= "Syscache", key= "MethodName")     PublicList<sysparam>querysysparamlist () {returnSysparamservice.querylist (NULL); }        /*** Enter the saved key value and get the corresponding value.     This method is often used. * */     Publicstring Getsysparam (String key) {if( This. Sysparammap = =NULL){             This. Sysparammap =NewHashmap<string,string>();  for(Sysparam param:querysysparamlist ()) {Sysparammap.put (Param.getkey (), Param.getvalue ()); }        }        return  This. Sysparammap.get (key); }}

Our cache class Syscacheservice even if it's written. You can see that the first time we call the Querymenulist or Getsysparam method, if map is empty it will be taken from the database, if there is data inside the map, the data will be taken directly from the map. The data is saved as a key-value pair. When we want to invoke the data inside, we only need to inject syscacheservice into the Operation class, and then call the corresponding method.

to give an example, My data structure is this:

This is the parameter configuration table in my project, because it was an Oracle database, and later when I imported the data into the MySQL database and found that the field was named "Key" and "value", the query SQL statement would give an error, so it was replaced with "Keyaa" and "VALUEAA".

The Mycontroller class wants to use the value of the system configuration Sms_url:

 Public String Getsmsurl () {    =syscacheservice.getparam ("Sms_url");     return Sms_url;}

Inject the Syscacheservice object Syscacheservice in the Mycontroller class and invoke its method, passing in the parameter "Sms_url" is OK.

Later, I wondered if there was a better way to put the cache in a static class like a tool class, so that you wouldn't have to inject a syscacheservice every time you use the cache data. Here's how:

1. Add a servlet context listener to the configuration file, and when the servlet loads, put the syscacheservice in the static class

2. Declaring a method in a static class, the proxy Syscacheservice method call

  An XML configuration file adds a listener:

<!---    <listener>        <  Listener-class>            cn.wangze.listener.MyContextListener        </ Listener-class >    </ Listener >
The Mycontextlistener code is as follows:
 PackageCn.wangze.listener;ImportJavax.servlet.ServletContext;Importjavax.servlet.ServletContextEvent;ImportJavax.servlet.ServletContextListener;Importorg.springframework.web.context.support.WebApplicationContextUtils;Importcn.wangze.Constants;ImportCn.wangze.service.SysCacheService; Public classMycontextlistenerImplementsservletcontextlistener{@Override Public voidcontextdestroyed (Servletcontextevent arg0) {} @Override Public voidcontextinitialized (Servletcontextevent SCE) {ServletContext sc=Sce.getservletcontext (); Syscacheservice Syscacheservice= Webapplicationcontextutils.getwebapplicationcontext (SC). Getbean (Syscacheservice.class);    Constants.setsyscacheservice (Syscacheservice); }}

The code for the static class is as follows:

 PackageCn.wangze;ImportCn.wangze.service.SysCacheService; Public classConstants {Private StaticSyscacheservice Syscacheservice;  Public StaticSyscacheservice Getsyscacheservice () {returnSyscacheservice; }         Public Static voidSetsyscacheservice (Syscacheservice syscacheservice) {Constants.syscacheservice=Syscacheservice; }         Public Staticstring GetParam (String key) {returnSyscacheservice.getsysparam (key); }}

  Thus, every time we use the cache data, we simply introduce the constants static class and call the data directly with the class name + method name.

Practical scenarios for Java cache classes

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.