[Fast] get started quickly learn SpringBoot easy to use and convenient Spring Cache caching framework

Foreword

Cache, in development is very common. In highly concurrent systems, if there is no cache, purely a database to carry, then the pressure will be very large databases, downtime situation might even arise. This article will take you to learn Spring Cache caching framework.

Original Statement

[This article published on the Nuggets number Happyjava]. Happy Nuggets address: https://juejin.im/user/5cc2895df265da03a630ddca , Happy's personal blog: http://blog.happyjava.cn . Welcome to reprint, but declared by this section shall be retained.

Creating SpringBoot project

Quickly create SpringBoot project by Spring initialise, can refer to: http: //blog.happyjava.cn/articles/7.html

The introduction of dependence

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

EnableCaching open the cache

@Configuration
@EnableCaching
public class CacheConfig {

    /**
     * 默认就是这种配置,可以不写
     */
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager();
    }

}

In SpringBoot, the default cache is ConcurrentMapCacheManager way, do not write also possible. Here you can configure different cache implementations by CacheManager, such redis, EHCACHE like. The next chapter then explain.

There ConcurrentMapCacheManager constructor overloads a variable parameter,

It received a cacheName to the Senate, if you set the cache name, then the subsequent method can only use the cache settings here, otherwise it will throw an exception. If a constructor with no arguments, it is a variable cache manager.

Cacheable comment

Cacheable annotations are used to set the cache. Common annotated as follows:

value or cacheNames

Specify the use of the cache, in fact, is the above mentioned cacheName. If no arguments ConcurrentMapCacheManager, this can be customized according to their own use and other factors.

key

Cache key, just like Map, is key to the operation of the cache.

Here it is accepted SpEL expression. About SpEL expression, to be a brief description of the following:

We have the following methods:

@CachePut(value = "listUsers", key = "#username")
public List<String> updateCache(String username) {
    System.out.println("执行了updateCache方法");
    return Arrays.asList("Happyjava", "Hello-SpringBoot", System.currentTimeMillis() + "");
}

The parameters can be obtained by way of #paramName

There is a root object is used as follows:

@CachePut(value = "listUsers", key = "#root.methodName+#username")
public List<String> updateCache(String username) {
    System.out.println("执行了updateCache方法");
    return Arrays.asList("Happyjava", "Hello-SpringBoot", System.currentTimeMillis() + "");
}

In fact, no need to remember, prompted by IDEA intelligent and flexible to use:

Each parameter represents the meaning, I believe we are at a glance.

condition

Cache control condition, if you use this field, only the result is true, the result will be cached.

@Cacheable(value = "listUsers", condition = "#username.length()>5")
public List<String> listUsers(String username) {
    System.out.println("执行了listUsers方法");
    return Arrays.asList("Happyjava", "Hello-SpringBoot", System.currentTimeMillis() + "");
}

A cache arranged posted below example:

@Cacheable(value = "listUsers", key = "#root.methodName+#username", condition = "#username.equals('Happyjava')")
public List<String> listUsers(String username) {
    System.out.println("执行了listUsers方法");
    return Arrays.asList("Happyjava", "Hello-SpringBoot", System.currentTimeMillis() + "");
}

Only when the username parameter equal to "Happyjava" when not cached results, whether by repeatedly printing: to determine the "implementation of listUsers method."

CachePut comment

I believe the HTTP protocol familiar friends to see the name to know this is doing with the comment. We can update the cache by CachePut comment. Common and Cacheable its annotation is consistent. The following example is given of a cache update:

@CachePut(value = "listUsers", key = "#username", condition = "#username.equals('Happyjava')")
public List<String> updateCache(String username) {
    System.out.println("执行了updateCache方法");
    return Arrays.asList("Happyjava", "Hello-SpringBoot", System.currentTimeMillis() + "");
}

We can write a key value and the corresponding test Cacheable notes:

@Cacheable(value = "listUsers", key = "#username", condition = "#username.equals('Happyjava')")
public List<String> listUsers(String username) {
    System.out.println("执行了listUsers方法");
    return Arrays.asList("Happyjava", "Hello-SpringBoot", System.currentTimeMillis() + "");
}

Test results are expected: After calling CachePut method, Cacheable method returns a new result.

CacheEvict comment

This is a deleted comment. In addition to three commonly used parameters listed above, two notes, there is a allEntries, which is a Boolean parameter, the default is false, which means "to remove all cache." In the case of false, just delete the key corresponding to the cache, if true, it will delete all cached (of course, is the corresponding value).

@CacheEvict(value = "listUsers", key = "#username")
public void deleteCache(String username) {
    System.out.println("执行了deleteCache方法");
}

@CacheEvict(value = "listUsers", allEntries = true)
public void deleteAllCache() {

}

to sum up

Of course, this is just a quick start of Spring cache example, in fact, we more often than not such use. In a real project, with more to redis be used on the next article to explain it (in fact, is some configuration of things)

Reference Code

https://github.com/Happy4Java/hello-springboot

No information leading public concern

Search public Happyjava number [], [Reply] and [video] e-books, e-books you can get a lot of quality and big data, kafka, nginx, MySQL and other videos

关注Happyjava公众号

Guess you like

Origin www.cnblogs.com/happy4java/p/11224148.html