Recommend 5 very good Java distributed caching framework

Source: Internet
Author: User
Tags constructor json prepare socket xmlns jboss server memory java se

The five Java distributed caching frameworks we recommend are: Ehcache,cacheonix,asimplecache,jboss Cache,voldemort


1, Ehcache? Java Distributed caching framework

EhCache is a Java implementation of open source distributed caching framework, EhCache can effectively reduce the load on the database, you can keep the data in different server memory, when the need for data can be quickly accessed. At the same time the Ehcache extension is very simple, the official provision of cache configuration in several ways. You can pass in different parameters by declaring the configuration, configuring in the XML, configuring in the program, or invoking the constructor method.


Official website: http://ehcache.org/

Ehcache has the following characteristics:

The access speed is very fast and the performance is very good.
Multiple caching policies can be applied.
A hierarchical cache that allows users to specify which data is cached in the hard disk and which data is cached in memory.
Distributed caching can be done through RMI, pluggable APIs, and so on.
A listening interface with cache and cache manager.
Support for multiple cache manager instances and multiple cache regions for an instance.
The default provides hibernate cache implementations.

Ehcache Configuration Sample code:

<ehcache>  <diskstore path= "Java.io.tmpdir"/>   <defaultcache  maxelementsinmemory= "10000″ eternal=" false "timetoidleseconds=" 120″ 
Timetoliveseconds= "120″ overflowtodisk=" true "maxelementsondisk=" 10000000″ diskpersistent= "false" diskexpirythreadintervalseconds= "120″ memorystoreevictionpolicy=" LRU "/>  </ehcache> 


In the same Java cache framework, the Ehcache configuration is relatively simple and easy to get started with, and the biggest advantage is that it supports distributed caching


2, Cacheonix? High performance Java Distributed caching system The

Cacheonix is also a java-based distributed cluster caching system that can also help you implement distributed caching deployments.

Official web site: http://www.cacheonix.com/

Cacheonix features

    reliable distributed Java cache
     high availability through replication
    support generics cache APIs
    can be integrated with ORM framework
    Load balancing using data partitioning
    support non-multicast networks
    High Performance computing
    fast local Java cache
    distributed lock mechanism

Cacheonix schema

<?xml Version =" 1.0 "

<cacheonix xmlns= "Http://www.cacheonix.com/schema/configuration"             xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"             xsi:schemalocation= "Http://www.cacheonix.com/schema/configuration  http://www.cacheonix.com/schema/cacheonix-config-2.0.xsd ">    <server>        <listener>          <tcp  port= "8879"  buffer= "128k"/>       </listener>        <broadcast>          <multicast  multicastaddress= "225.0.1.2"  multicastport= "9998"  multicastttl= "0"/>        </broadcast>       <partitionedcache name= " Customer.cache ">   &Nbsp;      <store>              <lru maxelements= "10000"  maxbytes= "10MB"/>              <expiration idletime= "120s"/>     
     </store>       </partitionedCache>       <partitionedcache name= "Invoice.cache" >           <store>              <lru maxelements= "10000"  maxbytes= "10MB"/>              <expiration idletime= "120s"/>           </store>       </partitionedCache>        <Partitionedcache name= "Search.results.cache" >           <store>             <lru maxbytes= " 5MB "/>          </store>        </partitionedCache>    </server> </cacheonix>


Cacheonix Cached Access

Get Cacheonix instance from configuration

/**  * tester for cachemanager.  */public final class cacheonixtest extends testcase {   
private cacheonix cacheonix;    /**     * Tests getting an instance of 
Cachemanager using a default cacheonix configuration.     */   public void testgetinstance ()  {       assertnotnull ("Cacheonix created in setup ()  method should not
 be null ",  cacheonix); &NBSP;&NBSP;&NBSP}    /**     * sets up the fixture.
 this method is called before a test is executed.     * <p/>     * Cacheonix receives the  Default configuration from a <code>cacheonix-config.xml</code> found in a class path or     * using a file that name is defined by 
System parameter <code>cacheonix.config.xml<code>.
    */   protected void setup ()  throws exception {
      super.setup ();       // get cacheonix using a default cacheonix  configuration. the configuration       // is stored  in the conf/cacheonix-config.xml       cacheonix = 
Cacheonix.getinstance (); &NBSP;&NBSP;&NBSP}    /**     * tears down the fixture.  this method is called after a test is executeD.     */   protected void teardown ()  throws Exception  {      // cache manager has be be shutdown
 upon application exit.       // note that call to shutdown ()  here  Uses unregistersingleton       // set to true. this  is necessary to support clean restart on setup ()    
   cacheonix.shutdown (shutdownmode.graceful_shutdown, true);
      cacheonix = null;
      super.teardown (); &NBSP;&NBSP;&NBSP}}


Read cache

Cacheonix Cacheonix = Cacheonix.getinstance ();
cache<string, string> cache = Cacheonix.getcache ("My.cache");
String Cachedvalue = Cache.get ("My.key");

Setting up caching

Cacheonix Cacheonix = Cacheonix.getinstance ();
cache<string, string> cache = Cacheonix.getcache ("My.cache");
String Replacedvalue = cache.put ("My.key", "My.value");

Delete Cache

Cacheonix Cacheonix = Cacheonix.getinstance ();
cache<string, string> cache = Cacheonix.getcache ("My.cache");
String Removedvalue = Cache.remove ("My.key");


As an open source distributed caching framework, Cacheonix can meet the system architecture of midsize enterprise scale, which has a great effect on the improvement of systems performance.


3, Asimplecache? Lightweight Android Caching framework

Asimplecache is a lightweight caching framework based on Android, which has only one Java file, and Asimplecache can basically cache commonly used Android objects, including plain strings, JSON objects, serialized Java objects, byte arrays, and so on.


Official website: Https://github.com/yangfuhai/ASimpleCache

What can Asimplecache cache?

Asimplecache can basically cache commonly used Android objects, including but not limited to the following types:

Normal string
JSON object
Serialized Java Objects
byte array

Characteristics of Asimplecache

Lightweight, only one Java file
Complete and flexible configuration, you can configure the cache path, cache size, cache count, cache timeout, and so on.
The timeout cache is automatically invalidated and automatically deleted from memory.
Multi-process Support

In Android development, we can replace the sharepreference configuration file with Asimplecache, especially if your application often reads data from the Internet, then use Asimplecache to cache the request data. After a period of time after the failure to re-read, which can reduce client traffic, while reducing server concurrency.

Sample code for Asimplecache

To set the cached data:

Acache Mcache = Acache.get (this);
Mcache.put ("Test_key1", "Test value");
Mcache.put ("Test_key2", "Test Value", 10);/Save 10 seconds, if more than 10 seconds to get this key, will be null
Mcache.put ("Test_key3", "Test Value", 2 * acache.time_day);//Save two days, if more than two days to get this key, will be null

Get Cached data:

Acache Mcache = Acache.get (this);
String value = mcache.getasstring ("Test_key1");

Asimplecache is the author of the Chinese, code hosted in the GitHub, but also used Asimplecache students can share the use of experience, to contribute to the cause of open source power.

4, JBoss cache? Java caching framework based on things

JBoss Cache is a Java-based transaction processing caching system that aims to build a Java-based cluster solution that can be either server or Java SE applications.


Official website: http://jbosscache.jboss.org/

Cluster high Availability

The JBoss cache will automatically replicate cached data and synchronize cached data between servers in the cluster, ensuring that any server restart does not affect the availability of the cache.

Cluster caching avoids system bottlenecks

JBoss Cache As the name implies is the use of caching to improve system scalability, when our web system encountered a large number of database reading and writing, the system bottleneck will appear in the database, JBoss cache can solve the frequent reading of the database problem, to solve this bottleneck.

In addition, because the JBoss cache caches are synchronized between each server in the cluster, the entire system is not affected by a cache server experiencing performance problems.

Standalone usage of JBoss cache

First, initialize the Treecache.

Treecache tree = new Treecache ();

Then read the configuration file

Propertyconfigurator config = new Propertyconfigurator ();
Config.configure ("configuration file. xml");

and start the service.

Tree.startservice ();

Because tree's structure is using node to access, Treecache here is very simple to use:

/level1/level2/node1 to represent the Node1 below the level two tree.

Now let's add a few objects to cache.

Tree.put ("/level1/level2/node1", "Key1", "value1");
String[] Array = {"1", "2", "3", "4"}
Tree.put ("/level3/array/", "myarray", array);

As you can see, Treecache can store any kind of object, including all the complex objects.

It's convenient to read objects,

string s = (string) tree.get ("/level1/level2/node1/", "Key1");

Value1 read it out.

Similarly:

String[] Sarr = (string[]) tree.get ("/level3/array/", "myarray");

System.out.println (Sarr[1]) will show 2

Last Stop service:

Tree.stopservice ();

Filecacheloader Example of JBoss cache

First, create a Filecache class that encapsulates the JBoss cache operation, as follows:

package com.javaeye.terrencexu.jbosscache;   import java.io.file;   import  java.util.map;   import org.jboss.cache.cache;   import  org.jboss.cache.defaultcachefactory;   import org.jboss.cache.fqn;   import  org.jboss.cache.node;   import org.jboss.cache.config.cacheloaderconfig;   import  org.jboss.cache.config.configuration;   import org.jboss.cache.loader.filecacheloader;    import org.jboss.cache.loader.filecacheloaderconfig;  /**   * <p>    * This is demo to illustrate how to use the  jboss cache to cache your   * frequently accessed Java  objects in order to dramatically improve   * the performance  of your applications. this makes it easy to remove   * data access bottlenecks, such  as connecting to a database.   * </p>   * <p >   * as a rule of thumb, it is recommended that  the FileCacheLoader not    * be used in a highly  concurrent, transactional or stressful environment,   * ant its  use is restricted to testing.   * </p>   *    *
  @author  TerrenceX   *   *  @param  <T>   */   public class filecache<t> {       /**        * the jboss cache, used to cache frequently accessed  java objects.       */       private cache<string,  T> cache;       /**       * @ constructor       *  @param  fscacheloaderlocation the file  system location to store the cache       */        public filecache (file fscacheloaderlocation)  {    
       cache = initcache (fscacheloaderlocation);       }       /**       *  Create a cache and whose cache loader type is file cache  Loader       *        *  @param   Fscacheloaderlocation the file position used to store the cache.        *        *  @return  Cache        */       public cache<string, t> initcache (File  fscacheloaderlocation)  {           // initiate  a FileCacheLoader instance            Filecacheloader fscacheloader = new filecacheloader ();            // prepare the file cache loader configuration file  for File Cache Loader            Filecacheloaderconfig fscacheloaderconfig = new filecacheloaderconfig ();         &Nbsp;  fscacheloaderconfig.setlocation (Fscacheloaderlocation.tostring ());            fscacheloaderconfig.setcacheloader (fscacheloader);            // set configuration to file cache loader            fscacheloader.setconfig (fscacheloaderconfig);            // prepare the configuration  for cache           configuration config =  new configuration ();            Config.setcacheloaderconfig (New cacheloaderconfig ());         
  config.getcacheloaderconfig (). Addindividualcacheloaderconfig (Fscacheloaderconfig);           // create a cache through the default cache factory           return new DefaultCacheFactory<String, T>
(). Createcache (config);       }       /**       * Add a new node into the tree-node  hierarchy       *        *  @param  fqn  Full Qualified Name for the new node       *   @return        */       public Node< String, t> addnode (FQN&LT;STRING&GT;&NBSP;FQN)  {        
   return cache.getroot (). AddChild (FQN);       }       /**       * remove a specified node from the  tree-node hierarchy       *        *
  @param  fqn Full Qualified Name for the specified node       */       public void removenode (fqn< STRING&GT;&NBSP;FQN)  {           cache.removenode (FQN);        }       /**        * Add node information to the specified node.        *        *  @param  fqn Full Qualified  name for the specified node       *  @param  key  the key of the node information       *  @param  value 
the value of the node information       */       public void addnodeinfo (Fqn<string> fqn, string key,  t value)  {           cache.put (Fqn, key,  value);       }       /**        * batch add node information to the specified node.        *        *  @param  fqn  full qualified name for the specified node       *
  @param  infos Node informations map       */        public void addnodeinfos (fqn<string> fqn, map<string, t>  infos)  {           cache.put (Fqn, infos);        }       /**        * Get node information from the specified node.        *        *  @param  fqn full qualified  Name for the specified node       *  @param   key the key of the node information       * @ return       */       public t getnodeinfo (Fqn<string> fqn, string key)  {            return cAche.get (Fqn, key);       }       /**       * Remove node information from the specified  node.       *        *  @param  fqn  Full Qualified Name for the specified node        *  @param  key The key of the node information        */       public void removenodeinfo (fqn<string>  fqn, string key)  {            Cache.remove (Fqn, key);       }  }


The following is a test case:

package com.javaeye.terrencexu.jbosscache;   import java.io.file;   import  org.jboss.cache.fqn;   public class main {       public  static void main (String[] args)  {            FileCache<String> fileCache = new FileCache<String> (New file ( "D:\\tmp");           fqn<string> jimmyfqn =  fqn.fromstring ("/com/manager/jimmy");           Fqn< String> hansonfqn = fqn.fromstring ("/com/developer/hanson");            filecache.addnode (JIMMYFQN);            filecache.addnode (HANSONFQN);            Filecache.addnodeinfo (jimmyfqn,  "En-name",  "Jimmy zhang");            filecache.addnodeinfo (jimmyfqn,  "Zh-name",  "Zhang ji");            filecache.addnodeinfo (hansonfqn,  "En-name",  "Hanson Yang");            filecache.addnodeinfo (hansonfqn,  "Zh-name", ) Yang kuo ");           String enName =  Filecache.getnodeinfo (hansonfqn,  "En-name");            System.out.println (enname);       }  }

The results of the


Run are as follows:

-Jbosscache Mbeans were successfully registered to the Platform Mbean server.  
-JBoss C Ache Version:jbosscache ' Malagueta ' 3.2.5.GA  
Hanson Yang

generated cache file directory structure as follows:

d:/tmp/com.fdb/ Manage.fdb/jimmy.fdb/data.dat
D:/tmp/com.fdb/developer.fdb/hanson.fdb/data.dat

Summary

JBoss Cache has more usage, if your system encounters a database bottleneck problem, you can consider using JBoss cache to solve.

5, Voldemort? A key-value (Key-value)-based caching framework

Voldemort is a distributed key-value caching system based on Java development, such as JBoss Cache, Voldemort also supports caching synchronization between multiple servers to enhance system reliability and read performance.


Official website: http://www.project-voldemort.com/voldemort/

Characteristics of Voldemort

Cached data can be replicated automatically between individual server nodes.
The cached data for each server is split horizontally and is therefore a subset of the total cache.
Keep the consistency of the cache strictly.
Provides server downtime quick recovery scenarios.
A configurable data storage engine.
Configurable method of data serialization.
Each data item has a version ID, which is used to guarantee the integrity and availability of the data.
Each cache node is independent, so the failure of any one node will not affect the normal operation of the system.

Voldemort key-value schematic diagram


Voldemort Logical architecture Diagram


Voldemort Physical architecture Diagram

How Voldemort is configured

Cluster configuration file:

<cluster>     <!-- The name is just to help  Users identify this cluster from the gui -->     < Name>mycluster</name>     <zone>       <
Zone-id>0</zone-id>       <proximity-list>1</proximity-list>     <zone>     <zone>        <zone-id>1</zone-id>       <proximity-list>0</proximity-list >     <zone>     <server>        <!-- the node id is a unique, sequential id beginning  with 0 that identifies each server in the cluster-->     &nBsp;  <id>0</id>       


Data storage mode configuration file:

<stores>       <store>       <name >test</name>       <replication-factor>2</replication-factor >       <preferred-reads>2</preferred-reads>        <required-reads>1</required-reads>       < Preferred-writes>2</preferred-writes>       <required-writes>1< /required-writes>       <persistence>bdb</persistence>        <routing>client</routing>       < Routing-strategy>consistent-routing</routing-strategy>       <
Key-serializer>           <type>string</type>           <schema-info>utf8</schema-info>        </key-serializer>       <value-serializer>            <type>json</type>            <schema-info version= "1" >[{"id": "Int32",  "Name": "String"}]</schema-info >           <compression>            <type>gzip<type>            </compression>       </value-serializer>        </store>   </stores>


Voldemort Use example

value = Store.get (key)
Store.put (key, value)
Store.delete (key)

Summary
The
Voldemort is a distributed caching system, so it can be applied to medium and large software projects, and performance is also good.

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.