Java Caching Technology

Source: Internet
Author: User
Tags delete cache

Recently again on the Iteye on the discussion of the Java cache Technology Post more, I do not understand, so the internet probably searched the next, to find an article, temporarily save, if useful to refer to later. This is posted, posts to: Http://

jnotify:, through the JNI technology, so that Java code can monitor the development of files in the folder change information, support Linux/windows/macos;
ehcache:, a widely used Java cache module, can do caching work using memory and file completion.
In Java Web projects, in order to improve the responsiveness of Web applications, it is possible to read the usual static files (including Css,js and various other images) into the memory cache in advance, which can reduce the IO operations of many file systems (which is often one of the bottleneck of project performance). However, this often has a disadvantage, that is, when the actual static file changes, the cache does not get a timely refresh, resulting in a certain lag phenomenon. Some projects may not be a problem, but for some projects, this problem must be addressed. There are basically two ways, one is to open a thread, constantly scan the file, and the cached file to make comparisons, determine the file time to modify, and the other is to use the system API to monitor the file changes. The disadvantage of the previous solution is obvious, time-consuming and laborious, the latter method needs to use JNI, and write some of the system's local library functions, fortunately, jnoify for us to prepare the work, directly to use it.

This article will simply give a small example of using jnotify and Ehcache to implement a static file cache.

The preparation of Jnotify
Before using jnotify, you need to "install" the jnotify. Jnotify uses JNI technology to invoke the local library of the system (the DLL file under win and the so file under Linux), which are nearly included in the download package. But if you use jnotify directly, you will often get an error:

    1. BASH   
    2. java.lang.unsatisfiedlinkerror: no jnotify in  java.library.path   
    3.     at java.lang.classloader.loadlibrary ( Unknown source)   
    4.     at java.lang.runtime.loadlibrary0 ( Unknown source)   
    5.     at java.lang.system.loadlibrary (Unknown  source)   
    6.     at net.contentobjects.jnotify.win32.jnotify_ Win32.<clinit> (Unknown source)   
    7.     at  Net.contentobjects.jnotify.win32.jnotifyadapterwin32.<init> (Unknown source)   
BASHjava.lang.UnsatisfiedLinkError:no jnotify in Java.library.pathat java.lang.ClassLoader.loadLibrary (Unknown SOURCE) at Java.lang.Runtime.loadLibrary0 (Unknown source) at Java.lang.System.loadLibrary (Unknown source) at Net.contentobjects.jnotify.win32.jnotify_win32.<clinit> (Unknown Source) at Net.contentobjects.jnotify.win32.jnotifyadapterwin32.<init> (Unknown Source)

This is because jnotify cannot find the required DLL or other library files, the solution is to put the Jnotify compressed package library files into the folder Java.library.path points to, generally under Windows can be placed in the [JRE installation directory]/ Under Bin.

The value of Java.library.path can be viewed through System.getproperty ("Java.library.path"), but even if you pass System.setproperty in the program (" Java.library.path "," Some/folder/path/contain/dll ") To change the value of Java.library.path, or can not be loaded into the corresponding DLL library file, because the JVM only read the Java.library.path at the beginning of the program load, and then use the Java.library.path, it is the first load to get that value. Some people think it's just a bug and report it to Sun ( but it seems like sun doesn't think it's a bug.
In addition to placing the DLL file in the [JRE installation directory]/bin, you can also manually specify the program's startup parameters:
Java-djava.library.path=some/folder/path/contain/dll method to achieve the goal.

Basic methods of Ehcache use
Ehcache is very easy to use, first we want to get an example of CacheManager. There are two methods of obtaining CacheManager, one is instance mode and one is singleton mode. Here we use the following one:

    1. CacheManager manager = new CacheManager ("Src/ehcache.xml"); instance mode
    2. Cachemanager.create (); //Singleton mode, default read Ehcache.xml under classpath as configuration file
    3. Cache cache = Cachemanager.getinstance (). GetCache ("Staticresourcecache");
    4. Staticresourcecache in the Ehcache.xml in advance to define the
CacheManager manager = new CacheManager ("Src/ehcache.xml"); instance mode cachemanager.create ();//Singleton mode, The default reads the Ehcache.xml under the Classpath as the configuration file cache cache = Cachemanager.getinstance (). GetCache ("Staticresourcecache");// Staticresourcecache in the Ehcache.xml in advance to define the

A simple example of ehcache.xml:
  1. Ehcache.xml:
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <ehcache updatecheck="false" dynamicconfig="false" >
  4. <diskstore path=""/>
  5. <cache name="Staticresourcecache"
  6. maxelementsinmemory="+"
  7. timetoidleseconds="7200"
  8. timetoliveseconds="7200" >
  9. </cache>
  10. </ehcache>
Ehcache.xml: <?xml version= "1.0" encoding= "UTF-8"? ><ehcache updatecheck= "false" dynamicconfig= "false" > <diskstore path= ""/>    <cache name= "Staticresourcecache" maxelementsinmemory= "1000" timetoidleseconds= "7200" timetoliveseconds= "7200" >    </cache></ehcache>

You can then use the cache instance to manipulate caching, the main way is
    1. Cache.get (Object key), Cache.put (new Element (object key, Object value)), Cache.remove (object key).
Cache.get (Object key), Cache.put (new Element (object key, Object value)), Cache.remove (object key).

Caching static files
First you need to scan the folder containing the static files, in order to facilitate our adoption of the Jodd Toolkit:

    1. import;   
    2. ...   
    3. filepathscanner fs = new  Filepathscanner () {  
    4.      @Override    
    5.     protected void  onfile (file file)  {  
    6.          cachestatic (file); //cache file functions, implementation see &NBSP;&NBSP;
    7.     }   
    8. };   
    9. fs.includedirs (true). Recursive (true). Includefiles (true)   
    10. Fs.scan ( Configurations.themes_path); //scan the folder containing the static files   
Import, ..... Filepathscanner fs = new Filepathscanner () {@Overrideprotected void onfile (file file) {cachestatic (file);//functions that cache files, implementation See back}};fs.includedirs (True). Recursive (True). Includefiles (True); Fs.scan (Configurations.themes_path);// Scan folders that contain static files

In general, if the client browser accepts files in gzip format, gzip compression can make the transmitted data significantly less, so consider the gzip compression of some cached static files in advance. Caching the contents of the read static file into the cache, if the static file can be transferred with gzip, the file content needs to be compressed first.

  1. Import; //JDK Self-brought gzip compression tool
  2. Import; the//gzip output is a byte stream
  3. Import; //jodd's Tool class
  4. Private static void cachestatic (file file) {
  5. if (!isstaticresource (File.getabsolutepath ()))
  6. return;
  7. String uri = Touri (File.getabsolutepath ()); //Generate a file ID
  8. FileInputStream in = null;
  9. StringBuilder builder = new StringBuilder ();
  10. try {
  11. in = new FileInputStream (file);
  12. BufferedReader br = new BufferedReader (
  13. new InputStreamReader (in, stringpool.utf_8));
  14. String StrLine;
  15. While ((StrLine = Br.readline ()) = null) {
  16. Builder.append (StrLine);
  17. Builder.append ("\ n"); !important
  18. }
  19. Fastbytearrayoutputstream bao = new Fastbytearrayoutputstream ();
  20. Gzipoutputstream go = new Gzipoutputstream (BAO);
  21. Go.write (Builder.tostring (). GetBytes ());
  22. Go.flush ();
  23. Go.close ();
  24. Cache.put (new Element (URI, Bao.tobytearray ())); Byte stream of cached files
  25. } catch (FileNotFoundException e) {
  26. E.printstacktrace ();
  27. } catch (Unsupportedencodingexception e) {
  28. E.printstacktrace ();
  29. } catch (IOException e) {
  30. E.printstacktrace ();
  31. } finally {
  32. Streamutil.close (in);
  33. }
  34. }
Import JAVA.UTIL.ZIP.GZIPOUTPUTSTREAM;//JDK Self-brought gzip compression tool import;// Gzip output is a byte stream import;//jodd tool class private static void Cachestatic (file file) {if (!isstaticresource ( File.getabsolutepath ())) return; String uri = Touri (File.getabsolutepath ());//Generate a file identity fileinputstream in = null; StringBuilder builder = new StringBuilder (); try {in = new FileInputStream (file); BufferedReader br = new BufferedReader (new InputStreamReader (in, stringpool.utf_8)); String strline;while ((strLine = Br.readline ()) = null) {builder.append (strLine); Builder.append ("\ n");//!important} Fastbytearrayoutputstream bao = new Fastbytearrayoutputstream (); Gzipoutputstream go = new Gzipoutputstream (bao); Go.write (Builder.tostring (). GetBytes ()); Go.flush (); Go.close (); Cache.put (New Element (URI, Bao.tobytearray ()));//byte stream of cache file} catch (FileNotFoundException e) {e.printstacktrace ();} catch (Unsupportedencodingexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finAlly {Streamutil.close (in);}} 

Use Jnotify to change the contents of the cache when the file changes

  1. Monitor the folder that Configurations.themes_path points to
  2. Jnotify.addwatch (Configurations.themes_path,
  3. jnotify.file_created |
  4. jnotify.file_deleted |
  5. jnotify.file_modified |
  6. Jnotify.file_renamed,
  7. true, new Jnotifylistener () {
  8. @Override
  9. public void filecreated (int wd,
  10. String RootPath, string name) {
  11. Cachestatic (new File (Rootpath+name)); Update Cache
  12. }
  13. @Override
  14. public void filedeleted (int wd,
  15. String RootPath, string name) {
  16. Cache.remove (Touri (RootPath) +name); //Delete cache entries
  17. }
  18. @Override
  19. public void filemodified (int wd,
  20. String RootPath, string name) {
  21. Cachestatic (new File (Rootpath+name));
  22. }
  23. @Override
  24. public void filerenamed (int wd,
  25. String RootPath, String oldname,
  26. String newName) {
  27. Cache.remove (Touri (RootPath) +oldname);
  28. Cachestatic (new File (Rootpath+newname));
  29. }
  30. });
Monitor Configurations.themes_path pointing to the folder Jnotify.addwatch (Configurations.themes_path, jnotify.file_created  | jnotify.file_deleted  | jnotify.file_modified | Jnotify.file_renamed, True,  new Jnotifylistener () {@Overridepublic void filecreated (int wd,string rootpath, String Name) {cachestatic (rootpath+name));//update cache} @Overridepublic void filedeleted (int wd,string rootpath, String Name) {Cache.remove (Touri (RootPath) +name);//delete cache entry} @Overridepublic void filemodified (int wd,string rootpath, String Name) {cachestatic (rootpath+name)), @Overridepublic void filerenamed (int wd,string rootpath, String oldname, String newName) {cache.remove (Touri (RootPath) +oldname); Cachestatic (new File (Rootpath+newname));}});

Java Caching Technology

Related Article

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: 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.