Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Spring use Cache     - Oracle 11g RMAN cross-platform transfer table space (Database)

- Java concurrent programming using the synchronized keyword ReentrantLock alternative primitive (Programming)

- Kubernetes (k8s) environment to build combat (Server)

- Five useful commands to manage file types and system time in linux (Linux)

- Ubuntu 14.04 Configuring cuda-convnet (Linux)

- Management Linux Container with Docker in Ubuntu (Linux)

- DM9000 bare Driver Design (Programming)

- To modify the existing user ID and comments GPG key (Linux)

- Gentoo: existing preserved libs problem solving (Linux)

- Install snort intrusion detection system on Debian (Linux)

- Linux console password solution (Programming)

- Ubuntu simple method to track multiple time zones (Linux)

- Upgrading KDE Plasma 5.3 in Ubuntu 15.04 (Linux)

- Node.js form --formidable (Programming)

- Linux system Passwd file detailed analysis (Linux)

- Why do you need close contact Rust 1.0 (Programming)

- TCP network communication Java Programming (Programming)

- Oracle set and remove columns unavailable (Database)

- Reported too many open files Linux solutions (Server)

- Ubuntu 12.04 / 14.04 users to install software LyX document processing (Linux)

 
         
  Spring use Cache
     
  Add Date : 2016-05-13      
         
         
         
  Version 3.1, Spring introduced support for the Cache. Using methods and principles are similar to Spring's transaction management support. Spring Cache is acting on the method, the core idea is this: When we would call a method on the cache of the method parameters and return the result as a key-value pair stored in the cache until the next using the same parameters will no longer be performing the method when the method is called, but get the results directly from the cache were returned. So when we use Spring Cache cache to ensure that our approach to the same method parameters must have the same return results.

Use Spring Cache we need to do two things:

Some methods use statement caching
Spring's support for the Cache Configuration
And Spring's support for transaction management, like, Spring Cache also has support for annotation-based and XML-based configuration in two ways. Let's take a look at annotation-based approach.

1 annotation-based support

Spring provides us with a few annotations to support Spring Cache. Its core is mainly @Cacheable and @CacheEvict. Use @Cacheable labeled method after Spring Cache caches return results, use @CacheEvict marking method will remove certain elements Spring Cache method of execution before or after execution. Here we shall describe in detail several annotations Spring annotation support for Cache-based offer.

1.1 @Cacheable

@Cacheable Can be marked on a method, it can be marked on a class. Means that when marked on a method which is supported by the cache, when the marker on a class indicates that all of the methods in this class are supported cache. For a support caching method, Spring will return the cached value after it is invoked to ensure that the results can be obtained when the method is performed next using the same parameters directly from the cache, without the need to execute the method again. Spring is the key to the cache, the value that is returned when the method return value caching method results, as key words, Spring also supported the two strategies, the default policy and custom policy, which will be described later. Note that when a cache function is not triggered when the support caching method is called inside the object. @Cacheable Can specify three attributes, value, key and condition.

1.1.1 value attribute specifies the name of the Cache

value property must be specified, which represents the return value is the current method will be cached on which the Cache, Cache of the corresponding name. Which may also be a plurality of Cache Cache, when you need to specify multiple Cache which is an array.

  @Cacheable ( "Cache1") // Cache is occurring on the cache1

  public User find (Integer id) {

      returnnull;

  }

  @Cacheable ({ "Cache1", "cache2"}) // Cache is occurring on the cache1 and cache2

  public User find (Integer id) {

      returnnull;

  }

1.1.2 using a custom key key attribute

      key attribute is used to specify when the Spring caching method returns the result of the corresponding key. The property supports SpringEL expressions. When we do not have the specified attribute, Spring uses the default policy to generate key. Here we take a look at a custom policy, as a default policy will be introduced separately later.

      Custom policy means that we can specify our key through Spring EL expressions. Here EL expressions can use parameters and their corresponding attributes. When using the method parameter we can directly use the "# parameter name" or "#p parameter index". Here are a few key parameters as an example of.

  @Cacheable (Value = "users", key = "# id")

  public User find (Integer id) {

      returnnull;

  }

 

  @Cacheable (Value = "users", key = "# p0")

  public User find (Integer id) {

      returnnull;

  }

 

  @Cacheable (Value = "users", key = "# user.id")

  public User find (User user) {

      returnnull;

  }

  @Cacheable (Value = "users", key = "# p0.id")

  public User find (User user) {

      returnnull;

  }

In addition to the use of the parameters as a key addition, Spring also provides us with a root object can be used to generate the key. By this we can get to the root object the following information.

Property name

description

Example

methodName

Current method name

# Root.methodName

method

The current method

# Root.method.name

target

Object currently being invoked

# Root.target

targetClass

The current class is called an object

# Root.targetClass

args

The current method parameters consisting of an array

# Root.args [0]

caches

Cache is called the current method used

# Root.caches [0] .name

When we use the root object's properties as the key, we can also "#root" omitted because Spring is the default property of the root object. Such as:

  @Cacheable (Value = { "users", "xxx"}, key = "caches [1] .name")

  public User find (User user) {

      returnnull;

  }

1.1.3 condition attribute specifies the condition occurred

      Sometimes we may not want to cache a method all return results. By condition attribute can achieve this functionality. condition property defaults to empty, all calls will be cached situations. The value is specified by SpringEL expression that cache when processing is true; indicates no caching that each call to the method which will be executed once when is false. Following example indicates that only when the user id is an even number will be cached.

  @Cacheable (Value = { "users"}, key = "# user.id", condition = "# user.id% 2 == 0")

  public User find (User user) {

      System.out.println ( "find user by user" + user);

      return user;

  }

1.2 @CachePut

      In Spring Cache support environment for the use of @Cacheable tagging method, Spring whether to cache elements present in the same key before each execution checks Cache, if there is no longer performing the method, but directly from the cache the results returned, otherwise the result will be the implementation and returns into the specified cache. @CachePut Can also declare a method supports caching feature. And @Cacheable except that @CachePut annotated method before executing the test results will not go before the existence of the cache have been executed, but every time the method is performed and the execution result is stored in the form of key-value pairs specified cache.

      @CachePut Also be marked in the upper classes and methods. When using @CachePut we can specify attributes with @Cacheable is the same.

  @CachePut ( "Users") // every time execution method, and the results stored in the specified cache

  public User find (Integer id) {

      returnnull;

  }

1.3 @CacheEvict

      @CacheEvict Is used to mark on the need to clear the cache element method or class. Which would indicate the implementation of all the methods of the trigger cache cleanup operations when the marker on a class. @CacheEvict Can specify attributes value, key, condition, allEntries and beforeInvocation. Which like semantics @Cacheable corresponding attribute value, key and the condition. That value represents clear action is (the name of the corresponding Cache) which occurs on the Cache; key which expressed the need to clear the key, if not specified the default policy will be used to generate the key; condition clears operating conditions occur. Here we introduce two emerging properties allEntries and beforeInvocation.

1.3.1 allEntries property

      allEntries is a boolean indicating whether the cache needs to be cleared of all elements. The default is false, meaning not. When you specify allEntries is true, Spring Cache will ignore the specified key. Sometimes we need to look at Cache to clear all the elements, than a clear element of a more efficient.

  @CacheEvict (Value = "users", allEntries = true)

  public void delete (Integer id) {

      System.out.println ( "delete user by id:" + id);

  }

1.3.2 beforeInvocation property

      The default cleanup after a corresponding method is executed successfully triggered, it will not trigger the cleanup method that is because if an exception is thrown unsuccessful return. Use beforeInvocation change trigger cleanup time when we specify when the property value is true, Spring will clear the cache before calling the method specified element.

  @CacheEvict (Value = "users", beforeInvocation = true)

  public void delete (Integer id) {

      System.out.println ( "delete user by id:" + id);

  }

      In fact, except @CacheEvict clear the cache elements, but when we use Ehcache as to achieve, we can get rid of their configuration Ehcache strategy, which is specified by Ehcache profile. Since the focus Ehcache not described herein, there is not much go into details, Ehcache For more information, please view my column about Ehcache.

1.4 @Caching

      @Caching Annotation allows us to specify multiple Spring Cache relevant annotation on a class or method. It has three attributes: cacheable, put and evict, are used to specify @ Cacheable, @ CachePut and @CacheEvict.

  @Caching (Cacheable = @Cacheable ( "users"), evict = {@CacheEvict ( "cache2"),

        @CacheEvict (Value = "cache3", allEntries = true)})

  public User find (Integer id) {

      returnnull;

  }

1.5 Use custom annotations

      Spring allows us to use a custom annotation when configuring cacheable method, provided on a custom annotation must be labeled with the corresponding annotations. As we have such a following use @Cacheable customize annotation labels.

@Target ({ElementType.TYPE, ElementType.METHOD})

@Retention (RetentionPolicy.RUNTIME)

@Cacheable (Value = "users")

public @interface MyCacheable {

}

      So we need to use @MyCacheable on caching method labeled can also achieve the same effect.

  @MyCacheable

  public User findById (Integer id) {

      System.out.println ( "find user by id:" + id);

      User user = new User ();

      user.setId (id);

      user.setName ( "Name" + id);

      return user;

  }

2 Spring's support for the Cache Configuration

2.1 Statement of Support for Cache

2.1.1-based annotation

      Spring Cache configuration support for annotation-based, first of all we need to introduce cache namespace in Spring configuration file, followed by you can enable Spring support for annotation-based Cache of.

< ? Xml version = "1.0" encoding = "UTF-8"?>

< Beans xmlns = "http://www.springframework.org/schema/beans"

  xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"

  xmlns: cache = "http://www.springframework.org/schema/cache"

  xsi: schemaLocation = "http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

    http://www.springframework.org/schema/cache

    http://www.springframework.org/schema/cache/spring-cache.xsd ">

  < Cache: annotation-driven />

< / Beans>

      < Cache: annotation-driven /> there is a cache-manager attribute is used to specify the name of the bean CacheManager corresponding currently used, the default is cacheManager, so when we CacheManager of id when cacheManager we can not specify this parameter, otherwise we need to specify.

      < Cache: annotation-driven /> You can also specify a mode attribute values ​​are optional proxy and aspectj. The default is to use a proxy. When the mode of proxy, caching method only when the outside is called Spring Cache action will occur, which means Spring Cache cache if a method is called in its statement inside the object it is not going to play a role. The mode when aspectj not have this problem. Also when using the proxy, only @Cacheable and other public methods will work on a label, the mode is set to aspectj If this method requires a non-public methods can also be used on the Spring Cache.

      In addition, < cache: annotation-driven /> You can also specify a proxy-target-class attribute, indicating whether or not you want the proxy class, the default is false. We mentioned earlier @ Cacheable, @ cacheEvict like may also be marked on the interface, which is no problem for proxy-based interface, it should be noted however that when we set the proxy-target-class true or mode of aspectj, the operation is directly based on class, as defined in the interface @Cacheable etc. Cache annotation will not be recognized, and that the corresponding Spring Cache will not play a role.

      Note that < cache: annotation-driven /> only to find definitions @Cacheable etc. in the same cache ApplicationContext comment.

2.1.2 XML-based configuration

      In addition to using annotations to declare support for the Cache outside, Spring also supports the use of XML to declare support for the Cache. This is mainly through similar aop: advice of cache: advice to carry out. In the cache namespace defines a cache: advice element is used to define a Cache for the advice. Its need to specify a cache-manager attribute, the default is cacheManager. cache: advice below can specify multiple cache: caching elements, which is somewhat similar to when @Caching annotated with annotation. cache: Under caching element and can specify cache: cacheable, cache: cache-put and cache: cache-evict elements, which are similar to @ Cacheable when using annotations, @ CachePut and @CacheEvict. Let's look at an example:

  < Cache: advice id = "cacheAdvice" cache-manager = "cacheManager">

      < Cache: caching cache = "users">

        < Cache: cacheable method = "findById" key = "# p0" />

        < Cache: cacheable method = "find" key = "# user.id" />

        < Cache: cache-evict method = "deleteAll" all-entries = "true" />

      < / Cache: caching>

  < / Cache: advice>

      The above configuration defines a cache named cacheAdvice of: advice, which specifies the cache findById methods and methods to find the cache named users. The approach here can also use wildcards "*", such as "find *" to represent any "find" method began.

      With cache: advice, we also need to introduce aop namespace, and then by aop: config specifies the definitions to be applied in good cacheAdvice which pointcut. Such as:

  < Aop: config proxy-target-class = "false">

      < Aop: advisor advice-ref = "cacheAdvice" pointcut = "execution (* com.xxx.UserService * (..).)" />

  

      The above configuration is indicated in the call to com.xxx.UserService any public method will use cacheAdvice corresponding cache: advice for Spring Cache process. More on Spring Aop content is not within the scope of this article to discuss.

2.2 Configuration CacheManager

      CacheManager Spring is a defined interface to manage Cache. Spring itself has provided us two CacheManager realization, one is based on the Java API ConcurrentMap, and the other is based on third-party Cache achieve --Ehcache, if we need to use other types of caches, we can do it yourself Spring of CacheManager AbstractCacheManager interface or an abstract class. The following are examples of Spring to look at the configuration has been achieved for the good of our two CacheManager of.

2.2.1 configuration based ConcurrentMap

  < Bean id = "cacheManager" class = "org.springframework.cache.support.SimpleCacheManager">

      < Property name = "caches">

        < Set>

            < Bean class = "org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p: name = "xxx" />

        < / Set>

      < / Property>

  < / Bean>

      The above configuration uses a SimpleCacheManager, which contains ConcurrentMapCache named "xxx" of.

2.2.2 configuration based Ehcache

  < -! Ehcache realization ->

  < Bean id = "cacheManager" class = "org.springframework.cache.ehcache.EhCacheCacheManager" p: cache-manager-ref = "ehcacheManager" />

  < Bean id = "ehcacheManager" class = "org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p: config-location = "ehcache-spring.xml" />

      The above configuration uses a Spring EhCacheCacheManager provided to generate a Spring CacheManager, which receives a Ehcache of CacheManager, because true for cached data or Ehcache. Ehcache of CacheManager by EhCacheManagerFactoryBean Spring provided to generate, which can be generated by specifying a Ehcache of CacheManager ehcache profile location. If not specified default will be in accordance with the rules of Ehcache take ehcache.xml file classpath root directory, if the file does not exist, you get Ehcache the corresponding jar package ehcache-failsafe.xml file as a configuration file. Ehcache more about here is not to say that it does not belong to the contents of this article, For more information on Ehcache content can refer to my previous series of articles published Ehcache can also refer to the official documents.

3 key generation strategy

      Key generation strategy, there are two, one is the default policy A custom policy.

3.1 default policy

      The default key generation strategy is generated by KeyGenerator, the default strategy is as follows:

If the method has no parameters, 0 is used as a key.
If only one parameter, then use this parameter as the key.
If the parameter is a surplus, then use the hashCode all parameters as a key.
      If we need to specify your own default policy, then we can implement your own KeyGenerator, and then specify KeyGenerator our Spring Cache use for KeyGenerator our own definition.

      Use annotation-based configuration through cache: annotation-driven specify.

  < Cache: annotation-driven key-generator = "userKeyGenerator" />

  < Bean id = "userKeyGenerator" class = "com.xxx.cache.UserKeyGenerator" />

      When using XML-based configuration through cache: advice to specify.

  < Cache: advice id = "cacheAdvice" cache-manager = "cacheManager" key-generator = "userKeyGenerator">

  < / Cache: advice>

 

      Note that the default generation strategy at this time all of us Cache Key is used with a KeyGenerator.

3.2 Custom Policy

      Custom policy means that we can specify our key through Spring EL expressions. Here EL expressions can use parameters and their corresponding attributes. When using the method parameter we can directly use the "# parameter name" or "#p parameter index". Here are a few key parameters as an example of.

  @Cacheable (Value = "users", key = "# id")

  public User find (Integer id) {

      returnnull;

  }

  @Cacheable (Value = "users", key = "# p0")

  public User find (Integer id) {

      returnnull;

  }

  @Cacheable (Value = "users", key = "# user.id")

  public User find (User user) {

      returnnull;

  }

  @Cacheable (Value = "users", key = "# p0.id")

  public User find (User user) {

      returnnull;

  }

      In addition to the use of the parameters as a key addition, Spring also provides us with a root object can be used to generate the key. By this we can get to the root object the following information.

Property name

description

Example

methodName

Current method name

# Root.methodName

method

The current method

# Root.method.name

target

Object currently being invoked

# Root.target

targetClass

The current class is called an object

# Root.targetClass

args

The current method parameters consisting of an array

# Root.args [0]

caches

Cache is called the current method used

# Root.caches [0] .name

        When we use the root object's properties as the key, we can also "#root" omitted because Spring is the default property of the root object. Such as:

  @Cacheable (Value = { "users", "xxx"}, key = "caches [1] .name")

  public User find (User user) {

      returnnull;

  }

4 Spring alone Ehcache

      Content described above is built-in support for Spring Cache, in fact, we can also use their own separate Ehcache of CacheManager or Ehcache objects Spring. By configuring EhCacheManagerFactoryBean and EhCacheFactoryBean in Application Context, we can put the corresponding EhCache CacheManager Ehcache objects and injected into other Spring bean object for use.

4.1 EhCacheManagerFactoryBean

    EhCacheManagerFactoryBean Spring is a built-in FactoryBean can produce Ehcache of CacheManager object. Which can be created through the property configLocation CacheManager of Ehcache configuration file specifies the path, the path is usually ehcache.xml file. If not specified configLocation, using a configuration file is created CacheManager default location, which is part of Ehcache own logic, that if there is a file in the classpath ehcache.xml root path, directly use the file as Ehcache configuration file, otherwise use ehcache-xxx.jar in ehcache-failsafe.xml file as a configuration file to create Ehcache of CacheManager. Also, if you do not want to create CacheManager use the default name (in ehcache.xml defined in the document, or define the CacheManager inside), you can specify by cacheManagerName property. The following is an example configuration EhCacheManagerFactoryBean.

  < ! - Defined CacheManager ->

  < Bean id = "cacheManager" class = "org.springframework.cache.ehcache.EhCacheManagerFactoryBean">

      < ! - Specifies the location of the configuration file ->

      < Property name = "configLocation" value = "/ WEB-INF / config / ehcache.xml" />

      < ! - Specifies the new name of CacheManager ->

      < Property name = "cacheManagerName" value = "cacheManagerName" />

  < / Bean>

4.2 EhCacheFactoryBean

      EhCacheFactoryBean is used to generate Ehcache of Ehcache object FactoryBean. There are two very important properties we can specify when defining EhcacheFactoryBean. CacheManager is a property that can be used to specify the CacheManager obtain or create Ehcache objects, if not specified will () Obtain or create a default CacheManager by CacheManager.create. Another important property is cacheName, which represents the current EhCacheFactoryBean corresponds CacheManager which one Ehcache object If not specified default beanName as cacheName. If the object corresponding to cacheName of Ehcache CacheManager does not exist, it will create a file called cacheName CacheManager the Cache objects. In addition, we can also specify by EhCacheFactoryBean of timeToIdle, timeToLive other attributes corresponding to the attributes you want to create Cache, pay attention to these properties only when there is no correspondence CacheManager new Cache Cache only works on existing Cache will not work, more property to refer to the Spring API documentation. There are also several properties is either Cache or newly created role of property already exists: statisticsEnabled, sampledStatisticsEnabled, disabled, blocking and cacheEventListeners, of which the first four default is false, the last one represents the current Cache specified CacheEventListener . Here is an example of a righteous EhCacheFactoryBean.


 < ! - Defined CacheManager ->

  < Bean id = "cacheManager" class = "org.springframework.cache.ehcache.EhCacheManagerFactoryBean">

      < ! - Specifies the location of the configuration file ->

      < Property name = "configLocation" value = "/ WEB-INF / config / ehcache.xml" />

      < ! - Specifies the new name of CacheManager ->

      < Property name = "cacheManagerName" value = "cacheManagerName" />

  < / Bean>

  < ! - Defines a Ehcache ->

  < Bean id = "userCache" class = "org.springframework.cache.ehcache.EhCacheFactoryBean">

      < Property name = "cacheName" value = "user" />

      < Property name = "cacheManager" ref = "cacheManager" />

  < / Bean>
     
         
         
         
  More:      
 
- Java learning problems encountered (Programming)
- Source MongoDB 3.2.1 installed on CentOS6.5 (Database)
- Linux more efficient than select a model epoll (Linux)
- Install the latest Eclipse IDE in Ubuntu (Linux)
- Linux vi command list (Linux)
- JavaScript subarray Deduplication (Programming)
- Linux environment has been running Tomcat how to deploy the new Tomcat (Server)
- Ubuntu 14.04 / 12.04 subscribe users to install software Liferea 1.10.10 (Linux)
- Python Flask environment to build (Linux)
- The REVERSE function of DB2 (Database)
- Ubuntu Tutorial: E: Failed to get lock / var / lib / apt / lists / lock - open (Linux)
- To create a secure network firewall with iptables Under Linux (Linux)
- Android code performance optimization tips (Programming)
- Understanding Linux firewall Iptables (Linux)
- Ubuntu 14.10 Apache installation and configuration (Server)
- To build a private Docker registry (Server)
- Install MATE desktop environment adjustment tools Mate Tweak 3.3.6 (Linux)
- Oracle 11g RMAN virtual private directory (Database)
- Will Laravel become the most successful PHP framework? (Programming)
- Radius server setup under CentOS (Server)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.