第七篇 : SpringBoot 整合 spring cache

文章首发于微信公众号《程序员果果》
地址:https://mp.weixin.qq.com/s/nqozEsvl5ZMaREMv2gZKlQ
本篇源码:https://github.com/gf-huanchupk/SpringBootLearning

一、JSR107

JSR107是Java的一套缓存规范,Java Caching定义了5个核心接口,分别是CachingProvider, CacheManager, Cache, Entry
Expiry

  • CachingProvider:定义了创建、配置、获取、管理和控制多个CacheManager。一个应用可
    以在运行期访问多个CachingProvider。

  • CacheManager:定义了创建、配置、获取、管理和控制多个唯一命名的Cache,这些Cache 存在于CacheManager的上下文中。一个CacheManager仅被一个CachingProvider所拥有。

  • Cache:是一个类似Map的数据结构并临时存储以Key为索引的值。一个Cache仅被一个 CacheManager所拥有。

  • Entry:是一个存储在Cache中的key-value对。

  • Expiry:每一个存储在Cache中的条目有一个定义的有效期。一旦超过这个时间,条目为过期 的状态。一旦过期,条目将不可访问、更新和删除。缓存有效期可以通过ExpiryPolicy设置。

    第七篇 : SpringBoot 整合 spring cache_第1张图片

二、Spring 缓存抽象

Spring从3.1开始定义了org.springframework.cache.Cacheorg.springframework.cache.CacheManager 接口来统一不同的缓存技术; 并支持使用JCache(JSR-107)注解简化我们开发;

  • 默认使用 ConcurrenMapCacheManager
  • Cache接口为缓存的组件规范定义,包含缓存的各种操作集合;
  • Cache接口下Spring提供了各种xxxCache的实现;如RedisCacheEhCacheCache , ConcurrentMapCache等;
  • 每次调用需要缓存功能的方法时,Spring会检查检查指定参数的指定的目标方法是否 已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法 并缓存结果后返回给用户。下次调用直接从缓存中获取。
  • 使用Spring缓存抽象时我们需要关注以下两点;
    • 1、确定方法需要被缓存以及他们的缓存策略
    • 2、从缓存中读取之前缓存存储的数据
第七篇 : SpringBoot 整合 spring cache_第2张图片

三、几个重要概念&缓存注解

第七篇 : SpringBoot 整合 spring cache_第3张图片
第七篇 : SpringBoot 整合 spring cache_第4张图片
第七篇 : SpringBoot 整合 spring cache_第5张图片

四、整合redis实现缓存

创建项目springboot-cache,引入spring-boot-starter-cachespring-boot-starter-data-redis 的依赖。

1. pom.xml



    4.0.0

    com.gf
    springboot-cache
    0.0.1-SNAPSHOT
    jar

    springboot-cache
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.5.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-cache
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            com.alibaba
            fastjson
            1.2.51
        

        
            mysql
            mysql-connector-java
            runtime
        

        
            org.projectlombok
            lombok
            1.18.2
            provided
        

        
            com.baomidou
            mybatis-plus-boot-starter
            3.0.1
        

        
            org.apache.velocity
            velocity
            1.7
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    




2. RedisConfig

我们用redis自定义CacheManager,同时自定义序列化方式。

注意:lombok 的getter setter 和 编辑器生成的 getter setter,有时会存在差异。字段 dID ,编辑器生成的是 getdId() ,而lombok 编译成的是getDId(),这中情况会可能会导致序列化成json时多出一个字段 json串出现 did 和 dId ,出现这种情况时,对与该实体可以弃用lombok,手动生成来解决。

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer();

        ParserConfig.getGlobalInstance().addAccept("com.gf.");

        //key序列化方式
        template.setKeySerializer(new StringRedisSerializer());
        //value序列化
        template.setValueSerializer(serializer);
        //value hashmap序列化
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();

        return template;
    }

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer();

        ParserConfig.getGlobalInstance().addAccept("com.gf.");

        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer))
                .disableCachingNullValues();

        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config);


        return builder.build();
    }


}

3. EmployeeServiceImpl

@Service
public class EmployeeServiceImpl extends ServiceImpl implements EmployeeService {

    @Cacheable(value = "emp" , key = "#root.args[0]" , condition = "#id > 0" , unless = "#result eq null")
    @Override
    public Employee getById(Serializable id) {
        System.out.println("getById");
        return super.getById( id );
    }

    @Override
    @CachePut(value = "emp", key = "#root.args[0].id", unless = "#result eq null ")
    public Employee updateEmployeeById(Employee entity) {
        boolean res = super.updateById( entity );
        if (res){
            return entity;
        }
        return null;
    }

    @CacheEvict(value = "emp", key = "#root.args[0]", condition = "#result eq true")
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById( id );
    }
    
}

4. 启动类 SpringbootCacheApplication

使用@EnableCaching开启缓存

@EnableCaching
@SpringBootApplication
public class SpringbootCacheApplication {

    public static void main(String[] args) {
        SpringApplication.run( SpringbootCacheApplication.class, args);
    }
}

之后我们通过postman测试。

源码地址:https://github.com/gf-huanchupk/SpringBootLearning

第七篇 : SpringBoot 整合 spring cache_第6张图片

你可能感兴趣的:(第七篇 : SpringBoot 整合 spring cache)