SpringBoot統合Redisキャッシュ


さぎょう


プロジェクトの業務量とデータ量が上昇すると、データベースの圧力が大きくなり、データアクセス速度が遅くなり、ページにデータをロードする際に回転する場合があり、ユーザー体験に影響を与える.この場合、キャッシュが役割を果たし、アクセスしたデータをredisに存在させ、再びこのデータにアクセスするとredisから直接取り出すことができ、効率を大幅に向上させる.

適用


Springbootベースのアプリケーション

POMファイルのインポート


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-cacheartifactId>
dependency>

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-redisartifactId>
dependency>

<dependency>
    <groupId>org.springframework.datagroupId>
    <artifactId>spring-data-redisartifactId>
dependency>

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-cacheartifactId>
dependency>

コンフィギュレーションクラス(ポリシー)

@Component
public class RedisConfig {

    @Bean
    public RedisTemplate<Object, Object> commonRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Object> ser = new Jackson2JsonRedisSerializer<Object>(Object.class);
        template.setDefaultSerializer(ser);
        return template;
    }

    @Bean
    @Primary
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1));
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }
}

注記を開く


起動クラスで注記@EnableCachingを開く
@SpringBootApplication
@MapperScan("com.purchasecloud.srm.dao")
@EnableDiscoveryClient //       
@EnableCaching
@EnableFeignClients
public class PurchasecloudSrmUserApplication {

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

共通のキャッシュ構成の抽出
サービスに作用する
@CacheConfig(cacheNames=ModuleName.SRM_USER) //         

キャッシュ注記


クエリー時に注記をキャッシュする
/**
     *     :
 *      *   @Cacheable:
 *      *   1、      ,    Cache(    ),  cacheNames       ;
 *      *      (CacheManager        ),           Cache       。
 *      *   2、 Cache        ,    key,         ;
 *      *      key          ;     keyGenerator   ,    SimpleKeyGenerator  key;
 *      *          SimpleKeyGenerator  key     ;
 *      *                        ;key=new SimpleKey();
 *      *                         :key=    
 *      *                         :key=new SimpleKey(params);
 *      *   3、             ;
 *      *   4、          ,     
 *      *
 *      *   @Cacheable                       ,          key     ,
 *      *                    ;                   ;
 *      *
 *      *     :
 *      *      1)、  CacheManager【ConcurrentMapCacheManager】      Cache【ConcurrentMapCache】  
 *      *      2)、key  keyGenerator   ,   SimpleKeyGenerator
 *      *
 *      *
 *      *       :
 *      *      cacheNames/value:         ;               ,      ,        ;
 *      *
 *      *      key:       key;       。             1-      
 *      *                SpEL; #i d;  id     #a0  #p0  #root.args[0]
 *      *              getEmp[2]
 *      *
 *      *      keyGenerator:key    ;      key       id
 *      *              key/keyGenerator:     ;
 *      *
 *      *
 *      *      cacheManager:       ;  cacheResolver       
 *      *
 *      *      condition:             ;
 *      *              ,condition = "#id>0"
 *      *          condition = "#a0>1":       》1        
 *      *
 *      *      unless:    ; unless      true,            ;           
 *      *              unless = "#result == null"
 *      *              unless = "#a0==2":          2,     ;
 *      *      sync:        
     * @param id
     * @return
     */
@Override
@Cacheable(value = {ModuleName.SRM_USER},key = "#id",condition = "#id.length()>0")
public ResponseResult queryById(String id) {
    ResponseResult result = new ResponseResult();
    SrmUser srmUser = srmUserMapper.selectById(id);
    result.setBody(srmUser);
    return result;
}

データ更新時にコメントを同時に更新する
/**
     * @CachePut:     ,       ;      
     *            ,      ;
     *     :
     *  1、       
     *  2、            
     *
     *     :
     *  1、  1   ;           ;
     *          key:1  value:lastName:  
     *  2、           
     *  3、  1   ;【lastName:zhangsan;gender:0】
     *                       ;
     *          key:   employee     :   employee  ;
     *  4、  1   ?
     *               ;
     *          key = "#employee.id":          id;
     *          key = "#result.id":      id
     *             @Cacheable key    #result
     *               ?【1           】
     *
     */
@Override
    @CachePut(value = {ModuleName.SRM_USER},key = "#result.body.id")
    public ResponseResult updateUser(SrmUser srmUser){
        ResponseResult result = new ResponseResult();
        return result;
//        int res = srmUserMapper.updateById(srmUser);
//        //        ,  result
//        return HandleResponseResult.checkUpdateValue(res,srmUser);
    }

削除時に注記も削除
 /**
     * @CacheEvict:    
     *  key:        
     *  allEntries = true:              
     *  beforeInvocation = false:              
     *                          ;             
     *
     *  beforeInvocation = true:
     *                        ,          ,     
     *
     *
     */
@Override
@CacheEvict(value = {ModuleName.SRM_USER})
public ResponseResult deleteUser(String id) {
    ResponseResult result = new ResponseResult();
    int res = srmUserMapper.deleteById(id);
    return HandleResponseResult.checkDeleteValue(res);
}