Spring Boot uses the cache method, springcache

Source: Internet
Author: User

Spring Boot uses the cache method, springcache

1. What is Cache?

The word Cache first came from the CPU design

When the CPU needs to read a piece of data, it first looks for it from the CPU cache and then immediately reads it and sends it to the CPU for processing, it reads data from the memory with a relatively slow speed and sends it to the CPU for processing. At the same time, it transfers the data block where the data is stored to the cache so that the whole data can be read from the cache in the future, no need to call the memory. This reading mechanism makes the CPU read cache hit rate very high (most CPUs can reach about 90%), that is to say, 90% of the data to be read by the CPU next time is in the CPU cache, only about 10% needs to be read from memory. This greatly saves the time for the CPU to directly read the memory, and does not need to wait for the CPU to read data. In general, the CPU reads data in the first cache and then the memory.

Later, the hard disk cache was first launched, and then the application cache, browser cache, Web Cache, and so on!

Cache is king !!

Spring Cache

Spring Cache is a complete set of application Cache solutions provided by Spring for Spring applications.

Spring Cache itself does not provide Cache implementation, but enables you to use various caches in Spring applications through unified interfaces, code specifications, configurations, annotations, and so on without worrying too much about the Cache details. With Spring Cache, you can easily use

Various cache implementations, including ConcurrentMap, Ehcache 2.x, JCache, and Redis.

Definition of Cache in Spring

The definition of cache in Sping, including in the org. springframework. Cache. cache interface,

It provides the following methods:

// Obtain the value <T> T get (Object key, Class <T> type) based on the specified key. // set the specified value according to the corresponding key, save to the cache void put (Object key, Object value); // reclaim the specified value void evict (Object key) based on the key)

From the definition, it is not difficult to see that the Cache is actually a key-value structure. We use a specified key to operate the corresponding value.

Cache Manager

The Cache is a set of key-value items. However, different caches may exist for different business themes in the project, such as the user Cache and department cache, these caches are logically separated. To differentiate these caches, org. springframework. Cache. CacheManager is provided to manage various caches. This interface only contains two methods.

// Obtain the Cache getCache (String name) of the corresponding topic based on the name; // obtain the Cache Collection of all topics <String> getCacheNames ();

In this interface, adding or deleting caches is not allowed. These operations should be completed within various CacheManager implementations and should not be made public.

Annotation-based Cache

Data Cache operations are not theoretically relevant to the business itself. We should separate the read/write operations on the Cache from the main code logic. Spring separation is based on annotation (of course, such as JSR-107 is based on Annotation ).

Spring provides a series of annotations, including @ Cacheable, @ CachePut, @ CacheEvict, and other annotations to simplify our cache operations. These annotations are located at org. springframework. cache. under the annotation package.

Ii. Example

A simple example of using Spring Cache for Spring Boot

We will build a Spring Boot Cache-based example step by step.

Create a Spring Boot project and introduce the following dependencies:

<dependencies>  <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-cache</artifactId>  </dependency>  <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId>  </dependency>  <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-test</artifactId>    <scope>test</scope>  </dependency></dependencies>

Among them, spring-boot-starter-cache is the key dependency of cache.

Modify the Application class and add the cache-enabled annotation @ EnableCaching.

@SpringBootApplication@EnableCachingpublic class CacheSimpleApplication {  public static void main(String[] args) {    SpringApplication.run(CacheSimpleApplication.class, args);  }}

@ EnableCache annotation starts the Spring cache mechanism, which will enable the application to detect all cache-related annotations and start working. At the same time, a CacheManager bean will be created and can be injected and used by our application.

Create a RestController class

@ RestController @ RequestMapping ("/") public class CacheController {@ Autowired private CacheTestService cacheTestService; /*** obtain information by ID ** @ param id * @ return */@ GetMapping ("{id}") public String test (@ PathVariable ("id ") string id) {return cacheTestService. get (id);}/*** Delete the information of an ID ** @ param id * @ return */@ DeleteMapping ("{id }") public String delete (@ PathVariable ("id") String id) {return cacheTestService. delete (id);}/*** save the information of an ID ** @ param id * @ return */@ PostMapping public String save (@ RequestParam ("id ") string id, @ RequestParam ("value") String value) {return cacheTestService. save (id, value);}/*** information with a new ID ** @ param id * @ return */@ PutMapping ("{id }") public String update (@ PathVariable ("id") String id, @ RequestParam ("value") String value) {return cacheTestService. update (id, value );}}

This class calls a Service to implement the actual addition, deletion, modification, and query operations.

Service implementation

Next, we need to implement our Service

@ Servicepublic class SimpleCacheTestServiceImpl implements CacheTestService {private static final Logger logger = LoggerFactory. getLogger (SimpleCacheTestServiceImpl. class); private final Map <String, String> enties = new HashMap <> (); public SimpleCacheTestServiceImpl () {enties. put ("1", "this no 1") ;}@ Autowired private CacheManager cacheManager; @ Override @ Cacheable (cacheNames = "test") public String get (String id) {// record the data generation time, used for testing and comparison long time = new Date (). getTime (); // print The used cacheManager logger.info ("The cacheManager is" + cacheManager); // when The data is not obtained from The cache, print The log logger.info ("Get value by id =" + id + ", The time is" + time); return "Get value by id =" + id + ", the value is "+ enties. get (id) ;}@ Override public String delete (String id) {return enties. remove (id) ;}@ Override public String save (String id, String value) {logger.info ("save value" + value + "with key" + id); enties. put (id, value); return value;} @ Override public String update (String id, String value) {return enties. put (id, value );}}

Cache

First, add the @ Cacheable annotation to the get method to run the code test.

We use postman for testing. the test address is http: // localhost: 8080/1, the browser responds to Get value by id = 1, the value isthis no 1, and the server console prints two lines of logs.

Get value by id=1,the value isthis no 1 Get value by id=1, The time is 1516004770216 

But when we refresh the browser address again, the browser returns normally, but the console no longer prints it, Because Spring no longer executes the method during the second call, but directly obtains the cached value. Spring Cache uses the function parameter as the key and caches the return value of the function in the Cache named test.

Here we use the @ Cacheable annotation. The cacheNames in the annotation specifies the Cache to be read here. In the cache of cacheName = "test", we will find the cache object whose key is id.

Delete cached data

In the above program, if we delete the specified value through the delete request, send the delete request to http: // localhost: 8080/1. At this time, the value has been deleted from the map, however, when we get the request to http: // localhost: 8080/1, we can still get the value because the data in the cache is not deleted when we delete the data, in the previous get method, the running results of the method are still saved, and Spring will not re-read, but directly read the cache. At this time, we add annotations BEFORE THE METHOD

@Override@CacheEvict(cacheNames = "test")public String delete(String id) {  return enties.remove(id);}

First, call the get request. the returned value is Get value by id = 1, and the value is 1.

Then, call the delete request. Delete the data from the cache and map and call the get request again. Then, the Get value by id = 1, the value is null, indicating that the value is indeed deleted from the cache.

Here we use the @ CacheEvict annotation. cacheNames specifies which cache to delete data. By default, the parameter of the method is used as the key to delete data.

Update Cache

When the program is here, if we run the post request, the request body is id = 1 & value = new1, then the console prints save value new value1 with key 1, the code will save the value to the map, but when we run the get request, we will find that the returned value is still in the previous state. This is what we can use

@Override@CachePut(cacheNames = "test", key = "#id")public String save(String id, String value) {  logger.info("save value " + value + " with key " + id);  return enties.put(id, value);}

Re-execute the code. We will first send a delete request to delete data from the map and cache. Then, send the post request and write the data to the map. After sending the get request, you will find that the value can be obtained correctly, and the Console does not print the log for obtaining data from the map.

The @ CachePut annotation is used here. The function of this annotation is to write the return value of the method to the cache specified by cacheNames according to the given key.

Similarly, we need to add the @ CachePut annotation to the put method so that the modification can also refresh the data in the cache.

Here, a simple cache application that includes adding, deleting, modifying, and querying is complete.

Iii. Focus

Several annotations

  • @ EnableCaching enable cache Configuration
  • @ Cacheable specifies that the return value of a method can be cached. Specify cache rules in Annotation properties.
  • @ Cacheput: cache the return value of the method to the specified key.
  • @ CacheEvict: deletes the specified cached data.

Note:

@ Cacheable and @ Cacheput both put the method execution results in the cache according to the specified key. @ Cacheable first checks whether data exists in the cache during execution. If yes, read from the cache directly. If no, execute the method and put the returned value into the cache. @ Cacheput first executes the method and then writes the execution result to the cache.The @ Cacheput method must be executed.

Complete sample code in https://github.com/ldwqh0/cache-test

Summary

The above section describes how to use cache in Spring Boot. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.