Spring cache mechanism instance code, spring cache instance

Source: Internet
Author: User

Spring cache mechanism instance code, spring cache instance

Spring's caching mechanism is flexible and can cache any Bean or Bean method in the container. Therefore, this cache mechanism can be cached at any level of the Java EE application.

The underlying layer of Spring cache also needs to be implemented using other caching tools, such as EhCache (Hibernate cache tool). The upper layer adopts unified API programming.

To use Spring cache, follow these three steps:

  • 1. Import context to the Spring configuration file: namespace
  • 2. enable caching in the Spring configuration file, specifically by adding <cache: annotation-driven cache-manager = "cache manager ID"/>
  • 3. Configure the cache manager. Different cache implementations have different configurations. For EhCache, You need to configure an ehcache. xml file first.

For example

<? Xml version = "1.0" encoding = "UTF-8"?> <Ehcache> <diskStore path = "java. io. tmpdir"/> <! -- Configure the default cache zone --> <defaultCache maxElementsInMemory = "10000" eternal = "false" timeToIdleSeconds = "120" timeToLiveSeconds = "120" maxElementsOnDisk = "10000000" bytes = "120" memoryStoreEvictionPolicy = "LRU"/> <! -- Configure the cache zone named users --> <cache name = "users" maxElementsInMemory = "10000" eternal = "false" overflowToDisk = "true" timeToIdleSeconds = "300" timeToLiveSeconds = "600 "/> </ehcache>

The aboveehcache.xmlAfter two cache zones are configured, the beans in Spring will be cached in these cache zones. Generally, the number of beans in the Spring container will be defined in ehcache.

Configure the cache manager in the Spring configuration file as follows. The first Bean is a factory Bean used to configure the CacheManager of EhCache, and the second Bean is the cache manager configured for the Spring cache, therefore, inject the first Bean into the second Bean.

<Cache: annotation-driven cache-manager = "cacheManager"/> <! -- Configure the CacheManager of EhCache to specify ehcache through configLocation. xml file location --> <bean id = "ehCacheManager" class = "org. springframework. cache. ehcache. ehCacheManagerFactoryBean "p: configLocation =" classpath: ehcache. xml "p: shared =" false "/> <! -- Configure the cache manager based on EhCache and inject the CacheManager of EhCache into the cache manager Bean --> <bean id = "cacheManager" class = "org. springframework. cache. ehcache. ehCacheCacheManager "p: cacheManager-ref =" ehCacheManager "> </bean>

The following is a complete Spring configuration,

<? 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: p = "http://www.springframework.org/schema/p" xmlns: cache = "http://www.springframework.org/schema/cache" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-bea Ns-4.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd "> <context: component-scan base-package =" com. service "/> <cache: annotation-driven cache-manager =" cacheManager "/> <! -- Configure the CacheManager of EhCache to specify ehcache through configLocation. xml file location --> <bean id = "ehCacheManager" class = "org. springframework. cache. ehcache. ehCacheManagerFactoryBean "p: configLocation =" classpath: ehcache. xml "p: shared =" false "/> <! -- Configure the cache manager based on EhCache and inject the CacheManager of EhCache into the cache manager Bean --> <bean id = "cacheManager" class = "org. springframework. cache. ehcache. ehCacheCacheManager "p: cacheManager-ref =" ehCacheManager "> </bean> </beans>

The following@CacheableFor example, demonstrate Spring EhCache-based Cache Usage.CacheableIt is used to modify classes or methods. If a class is modified, all methods in the class will be cached.

Class-level cache

For example, the following Bean classes are available,

@ Service ("userService") @ Cacheable (value = "users") public class UserServiceImpl implements UserService {@ Override public User getUsersByNameAndAge (String name, int age) {System. out. println ("getUsersByNameAndAge () is being executed ().. "); return new User (name, age) ;}@ Override public User getAnotherUser (String name, int age) {System. out. println ("executing getAnotherUser ().. "); return new User (name, age );}}

Class-based Cache caches all methods in the class. After caching, the program calls any method of the class instance. Spring will not actually execute this method as long as the input parameters are the same, instead, you can directly search for cached data based on input parameters!

For example, use cache data as follows,

Public static void test2 () {ApplicationContext ctx = new ClassPathXmlApplicationContext ("beans. xml "); UserService us = ctx. getBean ("userService", UserService. class); User u1 = us. getUsersByNameAndAge ("zhangsan", 50); // because the same parameter is used in the second call to the userService method, the real method will not be executed, // Spring will directly search for data User u2 = us from the cache by parameters. getAnotherUser ("Zhang San", 50); System. out. println (u1 = u2 );}

Output result,

GetUsersByNameAndAge ()..
True

As you can see, the above getAnotherUser () is not actually executed, because the input parameters are the same as the parameters passed in the previous method, so Spring directly extracts data from the cache.

Annotation in the Bean class above@CacheableIn addition to the required attribute value, the key, condition, and unless attributes are all used to set Spring storage policies. For Class-based Cache, by default, Spring uses parameters passed in as keys to cache the search results.

Of course, we can also modify the key policy so that Spring can follow other standards. For example, if the first parameter is the same as the key, search for the result in the cache.

Modify the Bean class as follows,

@Service("userService")@Cacheable(value="users", key="#name")public class UserServiceImpl implements UserService {  @Override  public User getUsersByNameAndAge(String name, int age) {

This means that if we pass in the same name, Spring will not actually execute the method. The method is actually executed only when the name is different. For example,

Public static void test2 () {ApplicationContext ctx = new ClassPathXmlApplicationContext ("beans. xml "); UserService us = ctx. getBean ("userService", UserService. class); User u1 = us. getUsersByNameAndAge ("Zhang San", 50); // after changing the key parameter of @ Cacheable to key = "# name", the following method can be executed. User u2 = us. getAnotherUser ("Li Si", 50); System. out. println (u1 = u2 );}

You can see this timegetAnotherUser()The method is executed,

1. getUsersByNameAndAge () is being executed ()..
2. getAnotherUser () is being executed ()..
3 false

We can also set the condition attribute, for example,

@Service("userService")@Cacheable(value="users", condition="#age<100")public class UserServiceImpl implements UserService {  @Override  public User getUsersByNameAndAge(String name, int age) {

So for the following code, both methods will not be cached, and Spring will execute the real method to get the result each time,

Public static void test2 () {ApplicationContext ctx = new ClassPathXmlApplicationContext ("beans. xml "); UserService us = ctx. getBean ("userService", UserService. class); User u1 = us. getUsersByNameAndAge ("zhangsan", 500); User u2 = us. getAnotherUser ("Li Si", 500); System. out. println (u1 = u2 );}

Execution result,

GetUsersByNameAndAge ()..
GetAnotherUser ()..
False

Method-level cache

The method-level cache only works for the method. Different methods can be used to set unused cache areas, such as the following,

@ Service ("userService") public class UserServiceImpl implements UserService {@ Cacheable ("users1") @ Override public User getUsersByNameAndAge (String name, int age) {System. out. println ("getUsersByNameAndAge () is being executed ().. "); return new User (name, age) ;}@ Cacheable (" users2 ") @ Override public User getAnotherUser (String name, int age) {System. out. println ("executing getAnotherUser ().. "); return new User (name, age );}}

Use the following test code,

Public static void test2 () {ApplicationContext ctx = new ClassPathXmlApplicationContext ("beans. xml "); UserService us = ctx. getBean ("userService", UserService. class); // The method will be executed for the first time and cached by User u1 = us. getUsersByNameAndAge ("zhangsan", 500); // although the following methods pass in the same parameter, the cached data User u2 = us cannot be used because these two methods are in different cache regions. getAnotherUser ("Zhang San", 500); System. out. println (u1 = u2); // The User u3 is cached and will not be executed here. getAnotherUser ("Zhang San", 500); System. out. println (u3 = u2 );}

Execution result,

GetUsersByNameAndAge ()..
GetAnotherUser ()..
False
True

Use @ CacheEvict to clear the cache

The method modified by @ CacheEvict can be used to clear the cache and use@CacheEvictYou can specify the following attributes.

AllEntries: whether to clear the entire cache area

BeforeInvocation: whether to clear the cache before executing the method. It is cleared after the method is successfully executed by default.

Condiition and key, and@Cacheable.

The following is a simple example,

@ Service ("userService") @ Cacheable ("users") public class UserServiceImpl implements UserService {@ Override public User getUsersByNameAndAge (String name, int age) {System. out. println ("getUsersByNameAndAge () is being executed ().. "); return new User (name, age) ;}@ Override public User getAnotherUser (String name, int age) {System. out. println ("executing getAnotherUser ().. "); return new User (name, age);} // specify the cache @ CacheEvict (value =" users ") public void evictUser (String name, int age) {System. out. println ("-- Clearing" + name + "," + age + "corresponding cache --");} // specify to clear all cached data in the user cache @ CacheEvict (value = "users", allEntries = true) public void evictAll () {System. out. println ("-- clearing the entire cache --");}}

Below is the test class,

Public static void test2 () {ApplicationContext ctx = new ClassPathXmlApplicationContext ("beans. xml "); UserService us = ctx. getBean ("userService", UserService. class); // The system caches two methods: User u1 = us. getUsersByNameAndAge ("zhangsan", 500); User u2 = us. getAnotherUser ("", 400); // call the evictUser () method to clear the specified data in the buffer us. evictUser ("Li Si", 400); // the cache of Li Si and 400 is cleared before. The data returned by the following method will be cached again by User u3 = us. getAnotherUser ("Li Si", 400); System. out. println (us = u3); // false // The preceding data of Michael Jacob and 500 is cached. The following method will not be re-executed, and User u4 = us in the cache will be directly retrieved. getAnotherUser ("Zhang San", 500); System. out. println (u1 = u4); // Output true // clear the entire cache us. evictAll (); // because the entire cache has been cleared, the following code will be re-executed User u5 = us. getAnotherUser ("zhangsan", 500); User u6 = us. getAnotherUser ("Li Si", 400); System. out. println (u1 = u5); // outputs false System. out. println (u3 = u6); // output false}

Execution result,

GetUsersByNameAndAge ()..
GetAnotherUser ()..
-- Clearing the cache corresponding to Li Si and 400 --
GetAnotherUser ()..
False
True
-- Clearing the entire cache --
GetAnotherUser ()..
GetAnotherUser ()..
False
False

Summary

The above is all the content of the Spring cache mechanism instance code in this article. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.