传统mvc开发中在Servlet或普通java类中使用ehcache缓存

   之前在网上看过很多关于使用Hibernate自带的ehcache做二级缓存开发,结合了spring框架后对于访问的效率提高了不少,现在我把ehcahe从Hibernate脱离出来,在不使用hibernate的框架里,比如传统mvc:jsp+javabean+servlet中使用ehcache做二级缓存开发

 

   首先要使用ehcahe需要下载他的jar包 http://sourceforge.net/project/showfiles.php?group_id=93232 

   我用的是1.5.0的版本

 

   下载完毕后建立一个标准的java的web工程,需要将下载解压后文件夹中的ehcache-1.5.0.jar,ehcache-1.5.0-sources.jar,以及lib文件夹中的三个backport-util-concurrent-3.0.jar,commons-logging-1.0.4.jar,jsr107cache-1.0.jar,一共五个jar包拷入web工程的lib中去,这样此web工程就可以用ehcahe了,官方使用方法详见http://ehcache.sourceforge.net/samples.html

 

 

   ehcache在java类中的使用方法:

 

首先和在hibernate中是用ehcache一样,必须有ehcache的配置文件:ehcache.xml,这个文件在下载的压缩包中有,将其粘贴到工程的src下,按需求更改你的参数

 

我得配置是:

 

  1. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.          xsi:noNamespaceSchemaLocation="ehcache.xsd">
  3.     <!--
  4.     CacheManager Configuration
  5.     ==========================
  6.     An ehcache.xml corresponds to a single CacheManager.
  7.     
  8.     See instructions below or the ehcache schema (ehcache.xsd) on how to configure.
  9.     System property tokens can be specified in this file which are replaced when the configuration is loaded.
  10.     For example multicastGroupPort=${multicastGroupPort} can be replaced with the System property either
  11.     from an environment variable or a system property specified with a command line switch such as
  12.      -DmulticastGroupPort=4446.
  13.     DiskStore configuration
  14.     =======================
  15.     The diskStore element is optional. To turn off disk store path creation, comment out the diskStore
  16.     element below.
  17.     Configure it if you have overflowToDisk or diskPersistent enabled for any cache.
  18.     If it is not configured, and a cache is created which requires a disk store, a warning will be
  19.      issued and java.io.tmpdir will automatically be used.
  20.     diskStore has only one attribute - "path". It is the path to the directory where
  21.     .data and .index files will be created.
  22.     If the path is one of the following Java System Property it is replaced by its value in the
  23.     running VM. For backward compatibility these are not specified without being enclosed in the ${token}
  24.     replacement syntax.
  25.     The following properties are translated:
  26.     * user.home - User's home directory
  27.     * user.dir - User's current working directory
  28.     * java.io.tmpdir - Default temp file path
  29.     * ehcache.disk.store.dir - A system property you would normally specify on the command line
  30.       e.g. java -Dehcache.disk.store.dir=/u01/myapp/diskdir ...
  31.     Subdirectories can be specified below the property e.g. java.io.tmpdir/one
  32.     -->
  33.     <diskStore path="java.io.tmpdir"/>
  34.     <!--
  35.     CacheManagerEventListener
  36.     =========================
  37.     Specifies a CacheManagerEventListenerFactory, be used to create a CacheManagerPeerProvider,
  38.     which is notified when Caches are added or removed from the CacheManager.
  39.     The attributes of CacheManagerEventListenerFactory are:
  40.     * class - a fully qualified factory class name
  41.     * properties - comma separated properties having meaning only to the factory.
  42.     Sets the fully qualified class name to be registered as the CacheManager event listener.
  43.     The events include:
  44.     * adding a Cache
  45.     * removing a Cache
  46.     Callbacks to listener methods are synchronous and unsynchronized. It is the responsibility
  47.     of the implementer to safely handle the potential performance and thread safety issues
  48.     depending on what their listener is doing.
  49.     If no class is specified, no listener is created. There is no default.
  50.     -->
  51.     <cacheManagerEventListenerFactory class="" properties=""/>
  52.     <!--
  53.     CacheManagerPeerProvider
  54.     ========================
  55.     (Enable for distributed operation)
  56.     Specifies a CacheManagerPeerProviderFactory which will be used to create a
  57.     CacheManagerPeerProvider, which discovers other CacheManagers in the cluster.
  58.     The attributes of cacheManagerPeerProviderFactory are:
  59.     * class - a fully qualified factory class name
  60.     * properties - comma separated properties having meaning only to the factory.
  61.     Ehcache comes with a built-in RMI-based distribution system with two means of discovery of
  62.     CacheManager peers participating in the cluster:
  63.     * automatic, using a multicast group. This one automatically discovers peers and detects
  64.       changes such as peers entering and leaving the group
  65.     * manual, using manual rmiURL configuration. A hardcoded list of peers is provided at
  66.       configuration time.
  67.     Configuring Automatic Discovery:
  68.     Automatic discovery is configured as per the following example:
  69.     <cacheManagerPeerProviderFactory
  70.                         class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
  71.                         properties="peerDiscovery=automaticmulticastGroupAddress=230.0.0.1,
  72.                                     multicastGroupPort=4446timeToLive=32"/>
  73.     Valid properties are:
  74.     * peerDiscovery (mandatory) - specify "automatic"
  75.     * multicastGroupAddress (mandatory) - specify a valid multicast group address
  76.     * multicastGroupPort (mandatory) - specify a dedicated port for the multicast heartbeat
  77.       traffic
  78.     * timeToLive - specify a value between 0 and 255 which determines how far the packets will
  79.       propagate.
  80.       By convention, the restrictions are:
  81.       0   - the same host
  82.       1   - the same subnet
  83.       32  - the same site
  84.       64  - the same region
  85.       128 - the same continent
  86.       255 - unrestricted
  87.     Configuring Manual Discovery:
  88.     Manual discovery is configured as per the following example:
  89.     <cacheManagerPeerProviderFactory class=
  90.                           "net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
  91.                           properties="peerDiscovery=manual,
  92.                           rmiUrls=//server1:40000/sampleCache1|//server2:40000/sampleCache1
  93.                           | //server1:40000/sampleCache2|//server2:40000/sampleCache2"
  94.                           propertySeparator="," />
  95.     Valid properties are:
  96.     * peerDiscovery (mandatory) - specify "manual"
  97.     * rmiUrls (mandatory) - specify a pipe separated list of rmiUrls, in the form
  98.                             //hostname:port
  99.     The hostname is the hostname of the remote CacheManager peer. The port is the listening
  100.     port of the RMICacheManagerPeerListener of the remote CacheManager peer.
  101.     
  102.     Configuring JGroups replication:
  103.     <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory"
  104.                                      properties="connect=UDP(mcast_addr=231.12.21.132;mcast_port=45566;ip_ttl=32;
  105.                                      mcast_send_buf_size=150000;mcast_recv_buf_size=80000):
  106.                                      PING(timeout=2000;num_initial_members=6):
  107.                                      MERGE2(min_interval=5000;max_interval=10000):
  108.                                      FD_SOCK:VERIFY_SUSPECT(timeout=1500):
  109.                                      pbcast.NAKACK(gc_lag=10;retransmit_timeout=3000):
  110.                                      UNICAST(timeout=5000):
  111.                                      pbcast.STABLE(desired_avg_gossip=20000):
  112.                                      FRAG:
  113.                                      pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;shun=false;print_local_addr=false)"
  114.                                      propertySeparator="::"
  115.             />
  116.      The only property necessay is the connect String used by jgroups to configure itself. Refer to the Jgroups documentation for explanation
  117.      of all the protocols. The example above uses UDP multicast. If the connect property is not specified the default JGroups connection will be
  118.      used.       
  119.     -->
  120.     <cacheManagerPeerProviderFactory
  121.             class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
  122.             properties="peerDiscovery=automatic,
  123.                         multicastGroupAddress=230.0.0.1,
  124.                         multicastGroupPort=4446timeToLive=1"
  125.             propertySeparator=","
  126.             />
  127.     <!--
  128.     CacheManagerPeerListener
  129.     ========================
  130.     (Enable for distributed operation)
  131.     Specifies a CacheManagerPeerListenerFactory which will be used to create a
  132.     CacheManagerPeerListener, which
  133.     listens for messages from cache replicators participating in the cluster.
  134.     The attributes of cacheManagerPeerListenerFactory are:
  135.     class - a fully qualified factory class name
  136.     properties - comma separated properties having meaning only to the factory.
  137.     Ehcache comes with a built-in RMI-based distribution system. The listener component is
  138.     RMICacheManagerPeerListener which is configured using
  139.     RMICacheManagerPeerListenerFactory. It is configured as per the following example:
  140.     <cacheManagerPeerListenerFactory
  141.         class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
  142.         properties="hostName=fully_qualified_hostname_or_ip,
  143.                     port=40001,
  144.                     socketTimeoutMillis=120000"
  145.                     propertySeparator="," />
  146.     All properties are optional. They are:
  147.     * hostName - the hostName of the host the listener is running on. Specify
  148.       where the host is multihomed and you want to control the interface over which cluster
  149.       messages are received. Defaults to the host name of the default interface if not
  150.       specified.
  151.     * port - the port the RMI Registry listener listens on. This defaults to a free port if not specified.
  152.     * remoteObjectPort - the port number on which the remote objects bound in the registry receive calls.
  153.                          This defaults to a free port if not specified.
  154.     * socketTimeoutMillis - the number of ms client sockets will stay open when sending
  155.       messages to the listener. This should be long enough for the slowest message.
  156.       If not specified it defaults 120000ms.
  157.     -->
  158.     <cacheManagerPeerListenerFactory
  159.             class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/>
  160.     <!--
  161.     Cache configuration
  162.     ===================
  163.     The following attributes are required.
  164.     name:
  165.     Sets the name of the cache. This is used to identify the cache. It must be unique.
  166.     maxElementsInMemory:
  167.     Sets the maximum number of objects that will be created in memory
  168.     maxElementsOnDisk:
  169.     Sets the maximum number of objects that will be maintained in the DiskStore
  170.     The default value is zero, meaning unlimited.
  171.     eternal:
  172.     Sets whether elements are eternal. If eternal,  timeouts are ignored and the
  173.     element is never expired.
  174.     overflowToDisk:
  175.     Sets whether elements can overflow to disk when the memory store
  176.     has reached the maxInMemory limit.
  177.     The following attributes and elements are optional.
  178.     timeToIdleSeconds:
  179.     Sets the time to idle for an element before it expires.
  180.     i.e. The maximum amount of time between accesses before an element expires
  181.     Is only used if the element is not eternal.
  182.     Optional attribute. A value of 0 means that an Element can idle for infinity.
  183.     The default value is 0.
  184.     timeToLiveSeconds:
  185.     Sets the time to live for an element before it expires.
  186.     i.e. The maximum time between creation time and when an element expires.
  187.     Is only used if the element is not eternal.
  188.     Optional attribute. A value of 0 means that and Element can live for infinity.
  189.     The default value is 0.
  190.     diskPersistent:
  191.     Whether the disk store persists between restarts of the Virtual Machine.
  192.     The default value is false.
  193.     diskExpiryThreadIntervalSeconds:
  194.     The number of seconds between runs of the disk expiry thread. The default value
  195.     is 120 seconds.
  196.     diskSpoolBufferSizeMB:
  197.     This is the size to allocate the DiskStore for a spool buffer. Writes are made
  198.     to this area and then asynchronously written to disk. The default size is 30MB.
  199.     Each spool buffer is used only by its cache. If you get OutOfMemory errors consider
  200.     lowering this value. To improve DiskStore performance consider increasing it. Trace level
  201.     logging in the DiskStore will show if put back ups are occurring. 
  202.     memoryStoreEvictionPolicy:
  203.     Policy would be enforced upon reaching the maxElementsInMemory limit. Default
  204.     policy is Least Recently Used (specified as LRU). Other policies available -
  205.     First In First Out (specified as FIFO) and Less Frequently Used
  206.     (specified as LFU)
  207.     Cache elements can also contain sub elements which take the same format of a factory class
  208.     and properties. Defined sub-elements are:
  209.     * cacheEventListenerFactory - Enables registration of listeners for cache events, such as
  210.       put, remove, update, and expire.
  211.     * bootstrapCacheLoaderFactory - Specifies a BootstrapCacheLoader, which is called by a
  212.       cache on initialisation to prepopulate itself.
  213.     * cacheExtensionFactory - Specifies a CacheExtension, a generic mechansim to tie a class
  214.       which holds a reference to a cache to the cache lifecycle.
  215.     * cacheExceptionHandlerFactory - Specifies a CacheExceptionHandler, which is called when
  216.       cache exceptions occur.
  217.     * cacheLoaderFactory - Specifies a CacheLoader, which can be used both asynchronously and
  218.       synchronously to load objects into a cache.
  219.     RMI Cache Replication
  220.     Each cache that will be distributed needs to set a cache event listener which replicates
  221.     messages to the other CacheManager peers. For the built-in RMI implementation this is done
  222.     by adding a cacheEventListenerFactory element of type RMICacheReplicatorFactory to each
  223.     distributed cache's configuration as per the following example:
  224.     <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
  225.          properties="replicateAsynchronously=true,
  226.          replicatePuts=true,
  227.          replicateUpdates=true,
  228.          replicateUpdatesViaCopy=true,
  229.          replicateRemovals=true
  230.          asynchronousReplicationIntervalMillis=<number of milliseconds"
  231.          propertySeparator="," />
  232.     The RMICacheReplicatorFactory recognises the following properties:
  233.     * replicatePuts=true|false - whether new elements placed in a cache are
  234.       replicated to others. Defaults to true.
  235.     * replicateUpdates=true|false - whether new elements which override an
  236.       element already existing with the same key are replicated. Defaults to true.
  237.     * replicateRemovals=true - whether element removals are replicated. Defaults to true.
  238.     * replicateAsynchronously=true | false - whether replications are
  239.       asynchronous (true) or synchronous (false). Defaults to true.
  240.     * replicateUpdatesViaCopy=true | false - whether the new elements are
  241.       copied to other caches (true), or whether a remove message is sent. Defaults to true.
  242.     * asynchronousReplicationIntervalMillis=<number of milliseconds> - The asynchronous
  243.       replicator runs at a set interval of milliseconds. The default is 1000. The minimum
  244.       is 10. This property is only applicable if replicateAsynchronously=true
  245.     For the Jgroups replication this is done with:
  246.     <cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory"
  247.                             properties="replicateAsynchronously=truereplicatePuts=true,
  248.                             replicateUpdates=truereplicateUpdatesViaCopy=false,
  249.                             replicateRemovals=true,asynchronousReplicationIntervalMillis=1000"/>
  250.     This listener supports the same property than the RMICacheReplicationFactory. 
  251.     Cluster Bootstrapping
  252.     The RMIBootstrapCacheLoader bootstraps caches in clusters where RMICacheReplicators are
  253.     used. It is configured as per the following example:
  254.     <bootstrapCacheLoaderFactory
  255.         class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"
  256.         properties="bootstrapAsynchronously=true, maximumChunkSizeBytes=5000000"
  257.         propertySeparator="," />
  258.     The RMIBootstrapCacheLoaderFactory recognises the following optional properties:
  259.     * bootstrapAsynchronously=true|false - whether the bootstrap happens in the background
  260.       after the cache has started. If false, bootstrapping must complete before the cache is
  261.       made available. The default value is true.
  262.     * maximumChunkSizeBytes=<integer> - Caches can potentially be very large, larger than the
  263.       memory limits of the VM. This property allows the bootstraper to fetched elements in
  264.       chunks. The default chunk size is 5000000 (5MB).
  265.     Cache Exception Handling
  266.     By default, most cache operations will propagate a runtime CacheException on failure. An
  267.     interceptor, using a dynamic proxy, may be configured so that a CacheExceptionHandler can
  268.     be configured to intercept Exceptions. Errors are not intercepted.
  269.     It is configured as per the following example:
  270.       <cacheExceptionHandlerFactory class="com.example.ExampleExceptionHandlerFactory"
  271.                                       properties="logLevel=FINE"/>
  272.     Caches with ExceptionHandling configured are not of type Cache, but are of type Ehcache only,
  273.     and are not available using CacheManager.getCache(), but using CacheManager.getEhcache().
  274.     Cache Loader
  275.     A default CacheLoader may be set which loads objects into the cache through asynchronous and
  276.     synchronous methods on Cache. This is different to the bootstrap cache loader, which is used
  277.     only in distributed caching.
  278.     It is configured as per the following example:
  279.         <cacheLoaderFactory class="com.example.ExampleCacheLoaderFactory"
  280.                                       properties="type=int,startCounter=10"/>
  281.     Cache Extension
  282.     CacheExtensions are a general purpose mechanism to allow generic extensions to a Cache.
  283.     CacheExtensions are tied into the Cache lifecycle.
  284.     CacheExtensions are created using the CacheExtensionFactory which has a
  285.     <code>createCacheCacheExtension()</code> method which takes as a parameter a
  286.     Cache and properties. It can thus call back into any public method on Cache, including, of
  287.     course, the load methods.
  288.     Extensions are added as per the following example:
  289.          <cacheExtensionFactory class="com.example.FileWatchingCacheRefresherExtensionFactory"
  290.                              properties="refreshIntervalMillis=18000loaderTimeout=3000,
  291.                                          flushPeriod=whateversomeOtherProperty=someValue ..."/>
  292.     -->
  293.     <!--
  294.     Mandatory Default Cache configuration. These settings will be applied to caches
  295.     created programmtically using CacheManager.add(String cacheName).
  296.     The defaultCache has an implicit name "default" which is a reserved cache name.
  297.     -->
  298.     <defaultCache
  299.             maxElementsInMemory="1000"
  300.             eternal="false"
  301.             timeToIdleSeconds="120"
  302.             timeToLiveSeconds="120"
  303.             overflowToDisk="true"
  304.             diskSpoolBufferSizeMB="30"
  305.             maxElementsOnDisk="10000000"
  306.             diskPersistent="false"
  307.             diskExpiryThreadIntervalSeconds="120"
  308.             memoryStoreEvictionPolicy="LRU"
  309.             />
  310.     <!--
  311.     Sample caches. Following are some example caches. Remove these before use.
  312.     -->
  313.     <!--
  314.     Sample cache named sampleCache1
  315.     This cache contains a maximum in memory of 10000 elements, and will expire
  316.     an element if it is idle for more than 5 minutes and lives for more than
  317.     10 minutes.
  318.     If there are more than 10000 elements it will overflow to the
  319.     disk cache, which in this configuration will go to wherever java.io.tmp is
  320.     defined on your system. On a standard Linux system this will be /tmp"
  321.     -->
  322.     <cache name="sampleCache1"
  323.            maxElementsInMemory="10000"
  324.            maxElementsOnDisk="1000"
  325.            eternal="false"
  326.            overflowToDisk="true"
  327.            diskSpoolBufferSizeMB="20"
  328.            timeToIdleSeconds="300"
  329.            timeToLiveSeconds="600"
  330.            memoryStoreEvictionPolicy="LFU"
  331.             />
  332.     <!--
  333.     Sample cache named sampleCache2
  334.     This cache has a maximum of 1000 elements in memory. There is no overflow to disk, so 1000
  335.     is also the maximum cache size. Note that when a cache is eternal, timeToLive and
  336.     timeToIdle are not used and do not need to be specified.
  337.     -->
  338.     <cache name="sampleCache2"
  339.            maxElementsInMemory="1000"
  340.            eternal="true"
  341.            overflowToDisk="false"
  342.            memoryStoreEvictionPolicy="FIFO"
  343.             />
  344.     <!--
  345.     Sample cache named sampleCache3. This cache overflows to disk. The disk store is
  346.     persistent between cache and VM restarts. The disk expiry thread interval is set to 10
  347.     minutes, overriding the default of 2 minutes.
  348.     -->
  349.     <cache name="sampleCache3"
  350.            maxElementsInMemory="500"
  351.            eternal="false"
  352.            overflowToDisk="true"
  353.            timeToIdleSeconds="300"
  354.            timeToLiveSeconds="600"
  355.            diskPersistent="true"
  356.            diskExpiryThreadIntervalSeconds="1"
  357.            memoryStoreEvictionPolicy="LFU"
  358.             />
  359.     <!--
  360.     Sample distributed cache named sampleDistributedCache1.
  361.     This cache replicates using defaults.
  362.     It also bootstraps from the cluster, using default properties.
  363.     -->
  364.     <cache name="sampleDistributedCache1"
  365.            maxElementsInMemory="10"
  366.            eternal="false"
  367.            timeToIdleSeconds="100"
  368.            timeToLiveSeconds="100"
  369.            overflowToDisk="false">
  370.         <cacheEventListenerFactory
  371.                 class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>
  372.         <bootstrapCacheLoaderFactory
  373.                 class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/>
  374.     </cache>
  375.     <!--
  376.     Sample distributed cache named sampleDistributedCache2.
  377.     This cache replicates using specific properties.
  378.     It only replicates updates and does so synchronously via copy
  379.     -->
  380.     <cache name="sampleDistributedCache2"
  381.            maxElementsInMemory="10"
  382.            eternal="false"
  383.            timeToIdleSeconds="100"
  384.            timeToLiveSeconds="100"
  385.            overflowToDisk="false">
  386.         <cacheEventListenerFactory
  387.                 class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
  388.                 properties="replicateAsynchronously=falsereplicatePuts=false,
  389.                             replicateUpdates=truereplicateUpdatesViaCopy=true,
  390.                             replicateRemovals=false"/>
  391.     </cache>
  392.     <!--
  393.     Sample distributed cache named sampleDistributedCache3.
  394.     This cache replicates using defaults except that the asynchronous replication
  395.     interval is set to 200ms.
  396.     -->
  397.     <cache name="sampleDistributedCache3"
  398.            maxElementsInMemory="10"
  399.            eternal="false"
  400.            timeToIdleSeconds="100"
  401.            timeToLiveSeconds="100"
  402.            overflowToDisk="false">
  403.         <cacheEventListenerFactory
  404.                 class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
  405.                 properties="asynchronousReplicationIntervalMillis=200"/>
  406.     </cache>
  407.     
  408. </ehcache>

其中的<cache>元素中的参数都是你设定的缓存参数,这里介绍几个常用的,其余可去http://ehcache.sourceforge.net/查询

 

maxElementsInMemory ---你打算往缓存中放入的对象个数,如果对象个数放满会把最先放入的挤出缓存,FIFO原则

 

eternal ---缓存中对象是否为永久的,假如是,超时配置将被忽略,对象从不过期,这里设为false,遵循FIFO原则

 

timeToIdleSeconds---缓存中对象冷却时间,即你放入缓存中的对象在这个时间中不使用,时间过后会自动从缓存中清除,如果使用了某对象重新计时,但不会超过timeToLiveSeconds

 

timeToLiveSeconds---缓存中对象存活时间,放入缓存的对象在这个时间过后会从缓存中清除

 

 overflowToDisk ---内存不足时,是否启用磁盘缓存,磁盘缓存需设置路径,此处不使用

 

<cache>元素的name参数标志一种cache的配置,如果不配置,系统回去找defaultCache

我这里使用了sampleCache1(在程序中获取cache时指定)

 

 

我的java测试类   CacheUtil

 

  1. package util;
  2. import net.sf.ehcache.Cache;
  3. import net.sf.ehcache.CacheManager;
  4. import net.sf.ehcache.Element;
  5. public class CacheUtil {
  6.     
  7.      
  8.      
  9.      public static void main(String[] args){
  10.          
  11.          //每当开始使用ehcache的时候都要是用CacheManager来创建Cache
  12.          String oldone = "test";
  13.          CacheManager manager = CacheManager.create();//单例模式创建CacheManager ,没有特殊情况一定要使用单例模式创建,不然会对系统浪费很大,且容易出错
  14.                   
  15.          Cache cache = manager.getCache("sampleCache1"); //使用了sampleCache1的缓存配置
  16.          Element element = new Element("key1"oldone );  //放入我想存入缓存的对象,这里是个字符串
  17.          cache.put(element);//缓存中放入ehcache的Element 
  18.          
  19.          Element element2 = cache.get("key1");    //取出放入缓存的那个叫key1的Element 
  20.          Object value = element2.getObjectValue();  //取出的对象是个Object 
  21.          
  22.          String newyf =(String)value;  //转化成实际的对象
  23.          
  24. //       System.out.println(newyf);
  25. //       System.out.println(cache.getSize());
  26. //       System.out.println(element2.getKey());
  27.          
  28.      }
  29. }

   这样,存取的过程就完了,是不是很简单,这样就可以在普通的javaweb开发中是用ehcache了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值