SpringBoot 2.0 Base Case (13): Manage Redis cache based on Cache annotation mode

Posted by lth2h on Tue, 20 Aug 2019 00:13:44 +0200

Text Source
 GitHub Address: Know a smile
https://github.com/cicadasmile/spring-boot-base

1. Introduction to Cache Caching

Starting with Spring3, define the Cache and CacheManager interfaces to unify different caching technologies;
The Cache interface is defined for the cached component specification and contains a collection of cached operations.
Spring provides various caching implementations under the Cache interface.
For example, RedisCache, EhCacheCache, ConcurrentMapCache, etc.

2. Core API

1. Cache cache interface
Define cache operations.Implementations are RedisCache, EhCacheCache, ConcurrentMapCache, and so on
2,CacheManager
Cache Manager, which manages various cache components
3. Cacheable is mainly for method configuration and can be cached according to the request parameters of the method

Cacheable Execution Process
 1) Before the method runs, query the Cache cache component under the name specified by cacheNames
 2) Cache is automatically created if no Cache component is present
 3) Find the contents of the cache in the Cache, using a key, which is the method's parameter by default
 4) keys are generated according to a policy; by default, keyGenerator is used, where custom configuration is used
 5) Call the target method without finding the cache;
6) Put the results returned by the target method into the cache

Cacheable Annotation Properties
 cacheNames/value: Specifies the name of the cache component used by the method to return the result, and can specify multiple caches
 Key: the key used to cache data
 Generator for key/keyGenerator:key, customizable
 cacheManager: Specify the cache manager
 cacheResolver: Specify the cache parser
 condition: specify qualified data to cache
 Unless: Denies caching; when unless specifies a condition that is true, the return value of the method will not be cached
 sync: whether to use asynchronous mode

4,CacheEvict
Clear Cache

CacheEvict: Cache Cleanup
 key: specify the data to be cleared
 allEntries = true: Specifies to clear all data in this cache
 beforeInvocation = false: Clear cache performed before method, exception not executed
 beforeInvocation = true: Clears the cache before the method runs, regardless of whether the method has an exception or not

5,CachePut
Ensure that the method is called and that the results are cached.
The difference with Cacheable is whether the method is called every time, often for updates, writes

CachePut: Executes the method and caches the results of the method execution
 Modify some data in the database and update the cache at the same time;
Execute process
 1) Call the target method first
 2) Then cache the results of the target method

6,EnableCaching
Turn on annotation-based caching
7,keyGenerator
key Generation Policy When Caching Data
8,CacheConfig
Unify the properties of cached annotations for this class

3. Integration with SpringBoot 2.0

1. Core Dependency

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

2. Cache Cache Configuration

import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Method;
@Configuration
public class CacheConfig {
    /**
     * key Generator for Custom Cache
     */
    @Bean("oneKeyGenerator")
    public KeyGenerator getKeyGenerator (){
        return new KeyGenerator() {
            @Override
            public Object generate(Object obj, Method method, Object... objects) {
                return "KeyGenerator:"+method.getName();
            }
        } ;
    }
}

3. Startup Class Annotation Open Cache

@EnableCaching            // Open Cache Cache Annotation
@SpringBootApplication
public class CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class,args) ;
    }
}

4. Cache Annotation Use Code

1) Encapsulate add-delete check interface

import com.boot.cache.entity.User;
public interface UserService {
    // Add, change, check, delete
    User addUser (User user) ;
    User updateUser (Integer id) ;
    User selectUser (Integer id) ;
    void deleteUser (Integer id);
}

2) Cache Note Use Cases

import com.boot.cache.entity.User;
import com.boot.cache.service.UserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
    // Use custom key generation policy
    // Cached result key:addUser::KeyGenerator:addUser
    @CachePut(value = "addUser",keyGenerator="oneKeyGenerator")
    @Override
    public User addUser(User user) {
        return user ;
    }
    // Cached result key:updateUser::2
    @CachePut(value = "updateUser",key = "#result.id")
    @Override
    public User updateUser(Integer id) {
        User user = new User() ;
        user.setId(id);
        user.setName("smile");
        return user;
    }
    // Cache result key: selectUser::3
    @Cacheable(cacheNames = "selectUser",key = "#id")
    @Override
    public User selectUser(Integer id) {
        User user = new User() ;
        user.setId(id);
        user.setName("cicadaSmile");
        return user;
    }
    // Delete the specified key: selectUser::3
    @CacheEvict(value = "selectUser",key = "#id",beforeInvocation = true)
    @Override
    public void deleteUser(Integer id) {

    }
}

5. Test Code Block

@RunWith(SpringJUnit4Cla***unner.class)
@SpringBootTest(classes = CacheApplication.class)
public class CacheTest {
    @Resource
    private UserService userService ;
    // Test: add, change, check, delete, four methods
    @Test
    public void testAdd (){
        User user = new User() ;
        user.setId(1);
        user.setName("cicada");
        userService.addUser(user) ;
    }
    @Test
    public void testUpdate (){
        userService.updateUser(2) ;
    }
    @Test
    public void testSelect (){
        userService.selectUser(3) ;
    }
    @Test
    public void testDelete (){
        userService.deleteUser(3) ;
    }
}

4. Source code address

GitHub Address: Know a smile
https://github.com/cicadasmile/spring-boot-base
 Code Cloud Address: Know a smile
https://gitee.com/cicadasmile/spring-boot-base

Topics: Java Spring github Database SpringBoot