SpringBoot+Cacheキャッシュ

5829 ワード

Spring bootがredisをキャッシュに使用する方法、keyの有効期間などのredisキャッシュをカスタマイズする方法、spring bootがredisをキャッシュに初期化する方法について説明します.@Cacheable,@CacheEveict,@CachePut,@CacheConfigなどの注釈とその属性の使い方を具体的なコードで紹介した.
 
1.Cacheの配備
1.1 redis依存およびデータソースの構成
構成pom.xml

    org.springframework.boot
    spring-boot-starter-redis
    1.4.6.RELEASE

プロファイルアプリケーション.yml
spring:
  datasource:
    bd:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://10.9.84.238:3306/bd?useUnicode=true&characterEncoding=utf8&useSSL=false
      username: root
      password: *****

    
  redis:
    database: 0
    host: 10.9.84.238
    password: *****
    port: 6379

1.2 CacheConfigの定義
Springのキャッシュ抽象を使用する場合、最も一般的な方法は、@Cacheableと@CacheEveict注釈をメソッドに追加することです.
beanにキャッシュ注記を追加する前に、Springによる注記駆動のサポートを有効にする必要があります.Java構成を使用する場合は、いずれかの構成に@EnableCachingを追加することで、注記駆動のキャッシュを起動できます.
Spring-data-redisはRedisCacheManagerを提供します.これはCacheManagerの実装です.RedisCacheManagerは、Redisサーバと連携し、RedisTemplateを使用してキャッシュ・エントリをRedisに格納します.
package com.zuoyehezi.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.util.Arrays;


@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport{

    @SuppressWarnings("rawtypes")
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //        
        rcm.setCacheNames(Arrays.asList("BDRedis","HelpRedis"));
        //        
        rcm.setDefaultExpiration(60*60*24*5);
        return rcm;
    }

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    //     key    
    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator(){
            //first parameter is caching object
            //second paramter is the name of the method, we like the caching key has nothing to do with method name
            //third parameter is the list of parameters in the method being called
            @Override
            public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
                StringBuffer sb = new StringBuffer();
                sb.append(target.getClass().getName()+".");
                sb.append(method.getName()+".");
                for(Object obj:params){
                    sb.append(obj.toString());
                }
                //       :com.zzyyfh.myredis.service.impl.HelloServiceImplgetFirstByMap{}
                return sb.toString();
            }
        };
    }

}

1.3キャッシュの使用
@Cacheableでは、value、key、conditionの3つのプロパティを指定できます.
パラメータ
説明する
example
value
キャッシュの名前springプロファイルで定義するには、少なくとも1つを指定する必要があります.
例:@Cacheable(value="mycache")@Cacheable(value={"cache 1","cache 2"}
key
キャッシュされたkeyは、空にすることができます.SpEL式で記述するように指定した場合、指定しない場合は、デフォルトでメソッドのすべてのパラメータで組み合わせられます.
@Cacheable(value=”testcache”,key=”#userName”)
condition
キャッシュの条件は、空であってもよく、SpELで記述し、trueまたはfalseを返し、trueのみがキャッシュを行う
@Cacheable(value=”testcache”,condition=”#userName.length()>2”)
package com.zuoyehezi.service.webHelp;

import com.zuoyehezi.Model.WebHelpRequest;
import com.zuoyehezi.mappers.febs.WebHelpMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author kangkai
 * @CreateTime 2019-08-14 16:44:00
 */
@Slf4j
@Service
public class WebHelpService {
    @Autowired
    private WebHelpMapper webHelpMapper;

    @Cacheable(value = "HelpRedis" , key = "'help_menuId_'+#request.menu_id+'_helpId_'+#request.help_id")
    public Map getHelpByMenu(WebHelpRequest request) {

        Map result = new HashMap<>();
        List> allReorderList = webHelpMapper.getHelpByMenu(request);

        result.put("help",allReorderList.get(0));

        return result;
    }

}