Springboot統合redisのノート


1.pom依存を先にインポート
       
    
		org.springframework.boot
		spring-boot-starter-data-redis
	
	
		redis.clients
		jedis
	

2.アプリケーション.ymlで構成されたredis情報
    
spring:
  redis:
      database: 0
      host: 192.168.147.144
      port: 6379
      password: 123456
      jedis:
          pool:
              max-active: 100
              max-idle: 3
              max-wait: -1
              min-idle: 0
      timeout: 1000

3.RedisConfigを作成する.JAva(Beans相当)
package com.company.springboot05.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.RedisCacheConfiguration;
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 org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


/**
 * redis   
 **/
//@Configuration     spring   xml     。
@Configuration
@EnableCaching//       
//  CachingConfigurerSupport,       KEY   。     。
public class RedisConfig extends CachingConfigurerSupport {

    /**
     *   redis     key        +   +             key
     *
     * @return
     */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    /**
     *     
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //  Spring   RedisCacheConfiguration ,       redis   ,                      
        //              ,   RedisCacheManager  builder.build()     cacheManager:
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();  //         ,  config              
        config = config.entryTtl(Duration.ofMinutes(1))     //            ,    Duration  
                .disableCachingNullValues();     //        

        //             set  
        Set cacheNames = new HashSet<>();
        //            
        cacheNames.add("my-redis-cache1");
        cacheNames.add("my-redis-cache2");

        //               
        Map configMap = new HashMap<>();
        configMap.put("my-redis-cache1", config);
        configMap.put("my-redis-cache2", config.entryTtl(Duration.ofSeconds(1200)));

        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)     //                cacheManager
                .initialCacheNames(cacheNames)  //           ,                  ,         
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
    }

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

        //  Jackson2JsonRedisSerializer         redis value (    JDK      )
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //  StringRedisSerializer         redis key 
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }

}

4.使用

//    @Cacheable            @CachePut                  value,key    
//    value         my-redis-cache1      (  cacheManager         )
//    key = "'book'+#bookId"  :      redis      'book'     bookId    
//    condition = "#bookId>10"  :        bookId>10      
//    @Cacheable(value = "my-redis-cache1", key = "'book'+#bookId",condition = "#bookId>10")
    @CachePut("my-redis-cache2")
    public TBoook selectByPrimaryKey(Long bookId) {
        return tBoookMapper.selectByPrimaryKey(bookId);
    }