Java cache Ehcache-core class and method introduction and use instance, javaehcache-

Source: Internet
Author: User

Java cache Ehcache-core class and method introduction and use instance, javaehcache-
Core classes and methods in Ehcache

 

The EhCache contains a CacheManager type, which is used to manage the cache. The Cache stores the Element object. The Element must be a key-value pair. The Cache is physically implemented in the memory or disk. The logical representation of these components is the class to be discussed below. Their methods provide programmable access methods.

 

CacheManager

Creates, accesses, and removes caches.

 

Create CacheManager

CacheManager supports two creation modes: Singleton mode and InstanceMode ).

In versions earlier than 2.5, any number of CacheManager with the same name can exist in the same JVM. Each time new CacheManager (...) is called, a new CacheManager instance is generated, regardless of the number of existing instances. When CacheManager. create (...) is called, The system returns the single-instance CacheManager corresponding to the existing configuration. If it does not exist, it creates one.


Versions later than 2.5 cannot have multiple CacheManager with the same name in the same JVM. The CacheManager () constructor that creates a non-singleton instance may break this rule, but will throw An NPE exception. If your code is to create multiple instances with the same name in the same JVM, use the static method CacheManager. create () always returns the corresponding name of CacheManager (if it already exists); otherwise, create one.

 

In fact, we can directly use EhCacheManagerFactoryBean [spring2.5.4] In Spring to help us complete the creation of CacheManager and see how it is created:

if (this.shared) {// Shared CacheManager singleton at the VM level.if (this.configLocation != null) {this.cacheManager = CacheManager.create(this.configLocation.getInputStream());}else {this.cacheManager = CacheManager.create();}}else {// Independent CacheManager instance (the default).if (this.configLocation != null) {this.cacheManager = new CacheManager(this.configLocation.getInputStream());}else {this.cacheManager = new CacheManager();}}if (this.cacheManagerName != null) {this.cacheManager.setName(this.cacheManagerName);}



The methods for creating EhCache2.5.2 and later versions are summarized as follows:

  • CacheManager. newInstance (Configuration configuration): Creates a new CacheManager object or returns the CacheManager object named in the corresponding Configuration that already exists.
  • CacheManager. create (): create a new default configuration of the Single Instance CacheManager, or return an existing single instance.
  • CacheManager. create (Configuration configuration Configuration), create a single instance CacheManager that corresponds to the name in the input configuration file, or return an existing single instance CacheManager.
  • New CacheManager (Configuration configuration Configuration), creates a new CacheManager, or throws an exception if the corresponding configuration CacheManager already exists or the Configuration parameter is null.

 

In Instance Mode, if the Cache uses MemoryStore, There is nothing special to note. However, if DIskStore is used, each CacheManager must have a different diskStore path. When a new CacheManager is created, check that no other CacheManager uses the same DiskStore path. If yes, an exception CacheException is thrown. If CacheManager is a part of a cluster, its listening port must be unique.

 

Singletonmode and Instance Mode can be used together without conflict.

 

Ehcache

All caches implement the Ehcache interface. Each cache has a name and attribute and contains an Element.

The cache in Ehcache is equivalent to a cache area in other cache systems.

 

Element

Element is the atomic unit stored in the cache. It has a key, a value, and access records. The Element is put into the cache or removed from the cache. They may also be removed due to expiration, depending on the configuration.


Use instance

The following is an example of using Ehcache.

Create a maven java project and add the Ehcache dependency to pom. xml.

    <!-- Ehcache -->    <dependency>        <groupId>net.sf.ehcache</groupId>        <artifactId>ehcache</artifactId>        <version>2.8.3</version>    </dependency>


The following is the java code. The code implementation function is very simple, that is, to create a CacheManager, store a Cache in it, store data in the cache, and retrieve data, in order to display the basic use of Ehcache.

/*** XXX.com Inc. * Copyright (c) 2004-2014 All Rights Reserved. */package com. test. encache; import net. sf. ehcache. cache; import net. sf. ehcache. cacheManager; import net. sf. ehcache. element;/***** @ author XXX * @ version $ Id: EncacheTest. java, v 0.1 August 8, 2014 5:30:03 XXX Exp $ */public class EncacheTest {// some configuration parameters // private final static String configFileName = "ehcache. xml "; // private final static int maxEntriesLocalHeap = 1000; private static CacheManager cacheManager; static String cacheName =" cache1 "; public static void main (String [] args) {ehcacheSetUp (); ehcacheUse ();} private static void ehcacheSetUp () {cacheManager = CacheManager. create (); // CacheConfiguration configuration = new CacheConfiguration (configFileName, // maxEntriesLocalHeap); // Cache cache = new Cache (configuration); cacheManager. addCache (cacheName);} private static void ehcacheUse () {Cache cache1 = cacheManager. getCache (cacheName); String key = "key1"; String value = "value1"; writeSomeData (cache1, key, value); Element element = readSomeData (cache1, key, value ); system. out. println (element);} private static void writeSomeData (Cache cache, String key, String value) {cache. put (new Element (key, value);} private static Element readSomeData (Cache cache, String key, String value) {return cache. get (key );}}

Program output:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".SLF4J: Defaulting to no-operation (NOP) logger implementationSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.[ key = key1, value=value1, version=1, hitCount=1, CreationTime = 1411807398768, LastAccessTime = 1411807398771 ]

The error message is caused by the absence of SLF4J related to log configuration.


Below we want to configure the log. First, add the dependency in pom. xml:

    <!-- SLF4J -->    <dependency>        <groupId>org.slf4j</groupId>        <artifactId>slf4j-log4j12</artifactId>        <version>1.6.1</version></dependency>
Then create the log4j configuration file log4j. properties:

# Root logger optionlog4j.rootLogger=INFO, file, stdoutlog4j.logger.com.test.encache.EncacheTest=INFO,file # Direct log messages to a log filelog4j.appender.file=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.file.File=C:\\logging.loglog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n # Direct log messages to stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


And place this file under the classpath of the Project. Here I create a maven project created with Eclipse and place it in the \ target \ classes folder under the main directory of the project.
Then add the logger initialization code to the Code:
private static final Logger logger    = LoggerFactory.getLogger(EncacheTest.class);

Then you can use:

logger.info("Setup ehcache");

Output:

2014-09-27 17:22:45 INFO  EncacheTest:35 - Setup ehcache2014-09-27 17:22:45 WARN  ConfigurationFactory:136 - No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/D:/MavenRepo/net/sf/ehcache/ehcache/2.8.3/ehcache-2.8.3.jar!/ehcache-failsafe.xml2014-09-27 17:22:46 WARN  DiskStorePathManager:162 - diskStorePath 'C:\Users\xiajun.xj\AppData\Local\Temp' is already used by an existing CacheManager either in the same VM or in a different process.The diskStore path for this CacheManager will be set to C:\Users\xiajun.xj\AppData\Local\Temp\ehcache_auto_created7989392067865891865diskstore.To avoid this warning consider using the CacheManager factory methods to create a singleton CacheManager or specifying a separate ehcache configuration (ehcache.xml) for each CacheManager instance.[ key = key1, value=value1, version=1, hitCount=1, CreationTime = 1411809766273, LastAccessTime = 1411809766276 ]



 

References:

Source Document
Can ehcache be used in jdbc? Configuration case and procedure

Sdfsdf
 
How to get started with Java application cache?

Session is not a concept. Let's simply talk about my personal views on Cache. You can think of it as a hashMap with a large capacity and get set data in it, because the data exists in the memory rather than in the database, the access speed is faster.

Common java caches include ehcache, oscache, and jcache. These caches are stored on a single machine, that is, in the memory of the local machine. In addition, I have used memcache for Distributed caches, it is deployed independently on one server, and multiple clients can share the cache.

Cache is generally used: 1. Concurrent requests must be responded in a timely manner. 2. Accelerate system response. For example, if a shopping website has a ranking list of items for sale, the data is sorted by N multi-Table Association queries in the database, and the data can be stored in the cache, when a page request is sent to view the ranking list, the data in the cache is directly obtained. The back-end scheduled task calculates the ranking result based on a certain interval and then replaces it with the current cache. This is a simple cache application example.

For specific usage instructions, you can refer to the instructions on various caches. Baidu has a lot to do. Easy to use ~

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.