Ehcache (01)--Introduction, basic operation

Source: Internet
Author: User

http://haohaoxuexi.iteye.com/blog/2112170

Directory

1 CacheManager

1.1 Construction Method Construction

1.2 Static method construction

2 Cache

Creation of the 2.1 cache

Ehcache is a tool for managing the cache, which can be stored in memory or stored on a hard disk. Its core is CacheManager, and all Ehcache applications start from CacheManager. It is used to manage cache, an app can have multiple CacheManager, and a cachemanager can have multiple caches. The cache internally holds a single element, and an element holds a pair of key and value, which is equivalent to a entry in the map.

1 CacheManager

CacheManager is the core of Ehcache and its primary responsibility is to create, remove, and access the cache. Only the cache inside the CacheManager can implement the function of caching data. All applications that use Ehcache start with the build CacheManager. When building CacheManager, we can build it directly through its construction method, or by using the static method provided by CacheManager.

1.1 Construction Method Construction

A new CacheManager object is generated each time the CacheManager is constructed using the constructor method, and the CacheManager is saved with the CacheManager corresponding name. An exception will be thrown when we build CacheManager if there is already a cachemanager with the same name in use. In addition, when multiple CacheManager correspond to Storepath, the files they hold on disk that contain cached information will be overwritten with each other.

1. using the default configuration

The default configuration is used when we use CacheManager's parameterless construction method to construct CacheManager. This situation will eventually look for the default configuration file to configure. Ehcache first will look for a configuration file called Ehcache.xml under the classpath to configure the CacheManager, if the file is not found, the CacheManager default configuration ehcache-failsafe.xml file is loaded, this file is in Ehcache Inside the. jar. A detailed explanation of how the configuration file is configured will be explained in a later article, with a simple look at a configuration file.

<ehcache xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"     xsi:nonamespaceschemalocation= "http// Ehcache.org/ehcache.xsd ">         <cache name=" test "maxbyteslocalheap=" 10M "/>      </ehcache>  

The root element of each configuration file is Ehcache, on which you can specify some CacheManager-level parameters. Each cache element under the Ehcache element represents a cached definition. You can specify some cache-level properties on the cache element. The following is an example of building CacheManager using the default configuration.

@Test public  void Testdefault () {     CacheManager CacheManager = new CacheManager ();     Outputs the XML format Text     System.out.println (Cachemanager.getactiveconfigurationtext ()) that corresponds to the configuration currently being used by the CacheManager;  }  

2. Use configuration as a parameter

Configurations are used to specify CacheManager configuration information, and other construction parameters specified in different ways will eventually be converted to a corresponding configuration object. The configuration object is then used to initialize the CacheManager.

@Test public  void Test () {     //new configuration information for a CacheManager config     = new ();     Create a new cache configuration information     cacheconfiguration cacheconfiguration = new Cacheconfiguration (). Name ("Test");     Specifies that the maximum heap memory value for the current cache is 100M     cacheconfiguration.maxbyteslocalheap (memoryunit.megabytes);     Add a cache     Configuration.addcache (cacheconfiguration);     Configuration.dynamicconfig (false);  Do not allow dynamic modification of configuration information     CacheManager CacheManager = new CacheManager (configuration);     Cache cache = Cachemanager.getcache ("test");     Cache.put (New Element ("Test", "Test"));     System.out.println (Cache.get ("test"). Getobjectvalue ());;  }  

3. InputStream as a parameter in XML -formatted configuration

When an XML-formatted configuration corresponds to InputStream as a parameter, Ehcache parses the XML and constructs a corresponding configuration object.

public void Testinputstream () throws IOException {     InputStream is = This.getclass (). getClassLoader (). getResourceAsStream ("/ehcache.xml");     CacheManager CacheManager = new CacheManager (is);     Is.close ();     System.out.println (Cachemanager.getactiveconfigurationtext ());  }  

4. The path of the configuration file in XML format as a parameter

After specifying the path for the configuration file in XML format, Ehcache gets the configuration file for the specified path, then gets its input stream, and constructs the CacheManager by using InputStream. The path here can be a relative path or an absolute path.

@Test public  void Testxmlpath () {     //This file path can be a relative path or an absolute path. The relative path is used here.     CacheManager CacheManager = new CacheManager ("Src/main/resources/ehcache/ehcache.xml");     System.out.println (Cachemanager.getactiveconfigurationtext ());  }  

5. URL as parameter for configuration in XML format

When a URL is used as a parameter, it is actually ehcache by getting the inputstream of the URL, and then using the InputStream to construct CacheManager in a inputstream construction CacheManager way.

@Test public  void Testurl () {     URL url = this.getclass (). GetResource ("/ehcache.xml");     CacheManager CacheManager = new CacheManager (URL);     System.out.println (Cachemanager.getactiveconfigurationtext ());  }

1.2 Static method construction

A series of static methods for building CacheManager objects are defined within CacheManager. This can be divided into two main categories, one is constructed by the Create () method and its overloaded method, which is constructed by the newinstance () method and its overloaded method. The Create () method constructs a single case, while the newinstance () method may be either singleton or multiple. Holding a CacheManager type of singleton object inside CacheManager, each time we call the Create () method and its overloaded method, Ehcache will determine whether the current singleton object is non-empty, and if not NULL, returns directly. Otherwise, a CacheManager object is constructed with the corresponding configuration to be assigned to Singleton and returned. When you call the Newinstance () method and its overloaded method to build CacheManager, Ehcache first determines whether we have previously created a CacheManager object with the same name, and if so, returns the CacheManager object directly. Otherwise a new cachemanager will be created to return. So calling CacheManager's Newinstance () series method constructs the CacheManager with the constructor method of the direct call CacheManager the difference between the CacheManager object is called newinstance () When a series method exists with the same name, it returns to the previous one without throwing an exception. In addition, CacheManager internally defines a getinstance () static method, which is called when it is called the Create () method without parameters.

1.create () Method

        There are altogether five create () methods defined within the CacheManager, corresponding to five newinstance of the CacheManager ( ) method, and each of the newinstance () methods corresponds to the CacheManager corresponding construction method. At the time of invocation, Ehcache will first determine whether the singleton held inside CacheManager is empty, and non-empty returns singleton, otherwise the instance object returned by the corresponding parameter's newinstance () is returned and assigned to Singleton.

public void Test () {     //creates a CacheManager singleton with the default configuration     CacheManager CacheManager = Cachemanager.create ();         Create a CacheManager with config config     = ...;//The Configuration object obtained in some way     CacheManager = Cachemanager.create (config);         Create CacheManager singleton     String configurationfilename = ...;//xml configuration file corresponding to the file name of the configurationfilename corresponding XML file definition. Contains path     CacheManager = Cachemanager.create (configurationfilename);         Create CacheManager singleton     inputstream is = ...;//the input stream corresponding to the XML configuration information obtained in some way     CacheManager = Cachemanager.create (is);         Create a cachemanager single URL URL with the configuration information corresponding to the URL     = ...;  The URL that corresponds to the XML configuration information obtained in some way     CacheManager = cachemanager.create (URL);  }  


2.newInstance ()
method

The

        has a total of five newinstance () methods defined within CacheManager, corresponding to the five construction methods of CacheManager. When the Newinstance () method is called, Ehcache checks to see if there is a cachemanager inside the CacheManager that has been created with the same name and returns the object if there is one, otherwise constructs a new CacheManager object to return. So the newinstance () method does not necessarily produce a new object.

public void Test () {     //Creates a CacheManager     cachemanager CacheManager = Cachemanager.newinstance () in the default configuration;         Create the CacheManager configuration     config = ...;//To get the Config object in some way     CacheManager = Cachemanager.newinstance (config);         Create CacheManager     String configurationfilename =.//xml configuration file corresponding file name, including path, as defined by configurationfilename corresponding XML file     CacheManager = cachemanager.newinstance (configurationfilename);         Create CacheManager     InputStream is = ...;//the input stream corresponding to the XML configuration information obtained in some way     CacheManager = Cachemanager.newinstance (is);         Create a CacheManager URL URL with the configuration information corresponding to the URL     = ...;  The URL that corresponds to the XML configuration information obtained in some way     CacheManager = cachemanager.newinstance (URL);  }  

1.3 CacheManager's Off

When we no longer need to use CacheManager, we need to close the CacheManager. Ehcache provides us with a hook to close the CacheManager, which is not available by default and can be turned on by setting the system Properties net.sf.ehcache.enableshutdownhook=true. But the official recommends that we call CacheManager's shutdown () method inside the program to close the current CacheManager.

2 Cache

An interface that handles caching is defined in Ehcache called Ehcache,cache is an implementation class for Ehcache. The cache is managed by CacheManager, and a cache object is generated using CacheManager. The cache contains one element object, which is usually stored in the Memorystore, but can also overflow to diskstore. The element contains a pair of key and value, where both key and value are object. The creation of the cache can be defined beforehand in the creation of the CacheManager, or it can be added to the cache by invoking the relevant method of the CacheManager instance later. The cache is thread-safe.

@Test public  void Test () {     CacheManager CacheManager = Cachemanager.create ();     Add a cache named CacheName with the default configuration.     Cachemanager.addcache ("CacheName");     Cache cache = Cachemanager.getcache ("CacheName");     Element ele = new Element ("key", "value");     Put the ele into the buffer cache     cache.put (ele);  }

Creation of the 2.1 cache

There are two main ways to create a cache, one created by the cache's construction method, and the other by CacheManager. A series of construction methods are defined in the cache, where we use the usual cacheconfiguration to construct the cache as an example.

@Test public  void Cache () {     //The maximum number of element saved in memory     int maxentrieslocalheap = 10000;     Cacheconfiguration cacheconfiguration = new Cacheconfiguration ("CacheName", maxentrieslocalheap);     Cacheconfiguration.overflowtooffheap (false);     Cache cache = New cache (cacheconfiguration);     Create CacheManager     CacheManager CacheManager = cachemanager.create () using the default configuration     ; Only the cache that is added to the CacheManager is useful     cachemanager.addcache (cache);     Cache.put (The new Element ("Key", "value"));     System.out.println (Cache.get ("key"));  }

Note: The cache must be added to the CacheManager directly by using the cache's construction method to be used.

The cache created by cachemanager means that we define the cache in the CacheManager corresponding configuration information, This will also instantiate the cache defined in the CacheManager and add it to the corresponding CacheManager when it is created. Depending on how you build the CacheManager, we have different ways to define the cache in CacheManager configuration information. In general there are two ways, one is to define the corresponding XML format of the configuration information, the other is to build CacheManager through the configuration to add cacheconfiguration to the configuration. Before we introduced CacheManager, we mentioned that each of the cache elements in the Ehcache configuration file represents a cache definition. A simple example is as follows:

<ehcache xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"     xsi:nonamespaceschemalocation= "http// Ehcache.org/ehcache.xsd ">         <cache name=" test "maxbyteslocalheap=" 10M "/>      

When building CacheManager with a configuration, we only need to add the cache definition, cacheconfiguration, to the configuration, and the sample code is as follows:

@Test public  void Cache2 () {     cacheconfiguration cacheconfiguration = new Cacheconfiguration ();     Cacheconfiguration.setname ("test");  Specify the cache name     cacheconfiguration.setmaxbyteslocalheap ("10M");   Specify the maximum available heap memory configuration     config = new configuration ();//Build an empty configuration     //Add cache configuration information to CacheManager     Config.addcache (cacheconfiguration);     CacheManager CacheManager = cachemanager.create (config);     System.out.println (Cachemanager.getoriginalconfigurationtext ());     Cache cache = Cachemanager.getcache ("test");     Cache.put (The new Element ("Key", "value"));  

Crud for 2.2 cache content

The crud for the cache content refers to CRUD operations on the elements that are saved in the cache.

(1) new elements

The new element can be done using the cache's put (element Ele) method. Element is a key-value pair form, and what we really want to cache is actually the value of element, but we can use key to distinguish between different value. The element also includes some additional information that we cache, such as the time of the cache. The element's key and value are similar to the key and value of map, and can be object objects.

public class Cachecrudtest {         private cachemanager CacheManager;         @Before public     Void before () {        CacheManager = Cachemanager.create ();        Cachemanager.addcache ("cache");     }         @After public     Void after () {        cachemanager.shutdown ();     }         /**     * add element to Cache *     /@Test public     void Create () {        Cache cache = Cachemanager.getcache ("Cache ");        Element ele = new Element ("key", "value");        Put the ele into the buffer cache        cache.put (ele);}     }  

(2) get elements

When we get the element we can do it through the Get () method of the cache, and the parameter it receives is the key of the element.

/**  * Reads the element from the Cache *  /@Test public  Void Read () {     Cache cache = Cachemanager.getcache ("cache");     The element     ele = Cache.get ("key") is obtained through key to the corresponding elements in the cache.     System.out.println (ele);     if (ele! = null) {//] Gets the cached value when the cached element is present        System.out.println (Ele.getobjectvalue ());}  }

(3) updating elements

When we put an element into the cache, if the same key element already exists in the cache, the old element is replaced with the new element, which means that some information about the previous element will be lost, such as the number of times hitcount and the creation time.

/**  * Update element  *  /@Test public  Void Update () {     Cache cache = Cachemanager.getcache ("cache");     Cache.put (New Element ("Key", "value1"));     System.out.println (Cache.get ("key"));     When adding an element, if an element of the same key already exists in the cache, the latter will be overwritten with the former     cache.put ("Key", "value2");     System.out.println (Cache.get ("key"));  }  

In addition, using the cache's replace (element Ele) method can also update the corresponding element in the cache. Unlike the direct put update, replace will only update the previous element when it has an element of the same key in the cache. Replace also overwrites the previous element information.

/**  * Update element  *  /@Test public  Void Update () {     Cache cache = Cachemanager.getcache ("cache");     Cache.put (New Element ("Key", "value1"));     System.out.println (Cache.get ("key"));     The replacement element is replaced only if there is already an element in the cache that has the corresponding key, otherwise it is not manipulated.     Cache.replace (New Element ("Key", "value2"));     System.out.println (Cache.get ("key"));  

(4) Deleting an element

The delete element is done through the Remove () method of the cache, which receives the key to delete the element as a parameter.

/**  * Remove an element based on key */  @Test public  void Delete () {     Cache cache = Cachemanager.getcache (" Cache ");     Removes an element     cache.remove ("key") based on key;     System.out.println (Cache.get ("key"));  

(This article is written based on Ehcache2.8.1)

Ehcache (01)--Introduction, basic operation

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