Spring Caching Cache

Simple demo

  • On the method you want to add cache plus @Cacheable notes, plus @EnableCaching on the class notes or directly loaded on startup class
package com.jsong.wiki.blog;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Component;

@EnableCaching
@Component
public class CacheService {

    @Cacheable("cache")
    public String getName(){
        System.out.println("cache");
        return "cache";
    }
}

When you call the getName method, the first call is not cached, it will execute the method body, when the second call is not executed method to obtain data directly in the cache.


Constrained applications available cache

  • application.yml
    as long as the name cache of cache,
spring:
  cache:
    cache-names:
      - cache

When accessing other cache it does not exist, will complain, not being given the time to start

java.lang.IllegalArgumentException: Cannot find cache named 'jsong' for Builder[public java.lang.String com.jsong.wiki.blog.CacheService.getName()] caches=[jsong] | key='' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false'

Turn off caching

Close the application cache
spring.cache.type = none

spring:
  cache:
    cache-names:
      - jsong
    type: none

Several important notes

@Cacheable

This annotation can set and get cache

public @interface Cacheable {
    @AliasFor("cacheNames")
    String[] value() default {};

    @AliasFor("value")
    String[] cacheNames() default {};

    String key() default "";

    String keyGenerator() default "";

    String cacheManager() default "";

    String cacheResolver() default "";

    String condition() default "";

    String unless() default "";

    boolean sync() default false;
}

The main parameters Support

  • cacheNames, value : same effect, are specified cache name when define both cacheNames and value when the value cacheNames and values to the same value.
    demo
    @Cacheable(value = "cache1")
    public String getName(){
        return "cache1";
    }

    @Cacheable(value = "cache1")
    public String getName2(){
        return "cache2";
    }

Test unit
when accessing getName (), there is not detected the cache, performing a method, the value placed into the cache and returns cache1, getName2 () and getName () value is denoted cache1 cache, so that when performing getName2 () found in the data cache, the method is not executed, take data directly from the cache, so there is no return cache2, but returns cahe1.

    @Test
    public void testCache(){
        System.out.println(cacheService.getName()); // cache1
        System.out.println(cacheService.getName2()); // cache1
    }

  • Key : currently cached key, and can be used with value, determine the cache. Support SpEL expressions (such as: "# parameter name" or "#p parameter index").
Attributes description Example (#root may be omitted)
methodName The current method name #root.methodName
method The current method #root.method.name
target The current object has been called #root.target
targetClass The current class is called an object #root.targetClass
args The current method parameter array consisting of #root.args[0]
caches The current method is called Cache used #root.caches[0].name

demo1

    @Cacheable(value = "cache1", key = "#root.method")
    public String getName() {
        return "cache1";
    }

    @Cacheable(value = "cache1", key = "#root.method")
    public String getName2() {
        return "cache2";
    }

Test unit
output cache1, cache2. Because the two caches call method is not the same method, the returned results of different

    @Test
    public void testCache(){
        System.out.println(cacheService.getName()); // cache1
        System.out.println(cacheService.getName2()); // cache2
    }

demo2

    @Cacheable(value = "cache1", key = "#root.target")
    public String getName() {
        return "cache1";
    }

    @Cacheable(value = "cache1", key = "#root.target")
    public String getName2() {
        return "cache2";
    }

Test unit
output returns cache1, cache1. Two method calls because the object is the same object.

    @Test
    public void testCache(){
        System.out.println(cacheService.getName()); // cache1
        System.out.println(cacheService.getName2()); // cache1
    }
  • for condition Condition : Only when conditions are met will go to check the cache, support SpEL expression

demo

    @Cacheable(value = "cache1", key = "#root.target")
    public String getName() {
        return "cache1";
    }

    @Cacheable(value = "cache1", key = "#root.target", condition = "#p0>#p1")
    public String getName2(int i, int j) {
        return "cache2";
    }

Unit Test
first call getName2 method cache1 that the cache data bits, and the condition condition is satisfied, the data output buffer cache1.
When you call getName2 second method, condition condition is not satisfied, the execution method, output data cache2.

    @Test
    public void testCache(){
        System.out.println(cacheService.getName()); // cache1
        System.out.println(cacheService.getName2(2,1)); // cache1
        System.out.println(cacheService.getName2(2,3)); // cache2
    }

@CachePut

This annotation is mainly set the cache, the cache can not get
its properties and @Cacheable similar, not repeat them here.

demo

    @Cacheable(value = "cache1", key = "#root.target")
    public String getName() {
        return "cache1";
    }

    @Cacheable(value = "cache1", key = "#root.target", condition = "#p0>#p1")
    public String getName2(int i, int j) {
        return "cache2";
    }

    @CachePut(value = "cache1", key = "#root.target", condition = "#p0>#p1")
    public String setCache1(int i, int j) {
        return "put-cache1";
    }

unit test

    @Test
    public void testCache(){
//        System.out.println(cacheService.getName2(2,1));
//        System.out.println(cacheService.getName2(2,3));
        cacheService.setCache1(2,1);
        System.out.println(cacheService.getName()); // put-cache1
    }

@CacheEvict

Clear cache
the method when executed, clearing the cache, if an error during the execution of the method, it is not clear the cache.
New property beforeInvocation when the value is true, before the method call to clear the cache, even if the method error, will clear the cache.
New property allEntries when the value is true, clear all cache, ignored key. When the value is false, the specified key cache empty, the default is false.

demo

    @Cacheable(value = "cache1", key = "#root.target")
    public String getName() {
        return "cache1";
    }

    @Cacheable(value = "cache1", key = "#p0", condition = "#p0>#p1")
    public String getName2(int i, int j) {
        return "cache2";
    }

    // cache1 指定key赋值
    @CachePut(value = "cache1", key = "#root.target", condition = "#p0>#p1")
    public String setCache1(int i, int j) {
        return "put-cache1";
    }

    // cache1 指定key赋值
    @CachePut(value = "cache1", key = "#p0", condition = "#p0>#p1")
    public String setCache2(int i, int j) {
        return "put-cache2";
    }

    // 清除cache1 指定key的缓存
    @CacheEvict(value = "cache1", key = "#root.target", condition = "#p0>#p1")
    public void evictCache(int i, int j) {
    }

    //  清除cache1的所有缓存,忽略key
    @CacheEvict(value = "cache1", allEntries = true, key = "#root.target", condition = "#p0>#p1")
    public void evictAllCache(int i, int j) {
    }

@Caching

More annotations may be defined attributes simultaneously
Cacheable
PUT
The evict

    @Caching(cacheable = @Cacheable(value = "cache1"), put = @CachePut(value = "cache2", key = "#root.target"), evict = @CacheEvict(value = "cache3", allEntries = true))
    public String caching() {
        return "caching";
    }

CacheManager

Spring comes in addition to the cache, these packages can also use the following cache management.

Generic
JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
EhCache 2.x
Hazelcast
Infinispan
Couchbase
Redis
Caffeine
Simple


Published 83 original articles · won praise 21 · views 50000 +

Guess you like

Origin blog.csdn.net/JsongNeu/article/details/103602907