Springboot統合redisについて(RedisTemplateを使用してredisを操作)


1.maven redis依存を追加


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

2.application.ymlまたはアプリケーションproperties構成redisパラメータ(ymlがtabを認識しないことに注意)
redis:
  host: 127.0.0.1
  port: 6379
  timeout: 1000
  pool:
   max-active: 8
   min-idle: 0
   max-idle: 8
   max-wait: -1
# Redis     (   0)
#spring.redis.database=0
# Redis     
#spring.redis.host=127.0.0.1
# Redis       
#spring.redis.port=6379
# Redis       (    )
#spring.redis.password=
#         (          )
#spring.redis.pool.max-active=8
#            (          )
#spring.redis.pool.max-wait=-1
#            
#spring.redis.pool.max-idle=8
#            
#spring.redis.pool.min-idle=0
#       (  )
#spring.redis.timeout=1000

3.CacheManager、RedisTemplateを書き換える
CacheManagerでsetDefaultExpirationキャッシュの有効期限を設定しても無効なようです.
package com.imm.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;


@Configuration
//@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600 * 12)
@EnableCaching
public class RedisAutoConfig extends CachingConfigurerSupport {

  
  @Bean
  public CacheManager cacheManager(RedisTemplate redisTemplate) {
      RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
      //        
      //Map expires = new HashMap<>();
      //expires.put("12h",3600 * 12L);
      //expires.put("1h",3600 * 1L);
      //expires.put("10m",60 * 5L);
      //rcm.setExpires(expires);
      
      //rcm.setDefaultExpiration(10); 	// 
      return rcm;
  }
  /*@Bean
  public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate redisTemplate = new RedisTemplate();
    redisTemplate.setConnectionFactory(factory);
    RedisSerializer stringRedisSerializer = new StringRedisSerializer();//Long            ;
    redisTemplate.setKeySerializer(stringRedisSerializer);
    return redisTemplate;
  }*/
  
  @Bean
  public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
     RedisTemplate template = new RedisTemplate<>();
     template.setConnectionFactory(connectionFactory);

     //  Jackson2JsonRedisSerializer         redis value 
     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;
  }
  
}

4.RedisTemplate操作LIST
/**
	 * redis   LIST    
	 * @param map
	 * @param isSql  1.  sql 0.   sql
	 * @return
	 */
	public List> doRedisList(Map map,int isSql){
		
	    //       key    
        String key = "";
        if(map.get("cacheKey")!=null){
        	key = map.get("cacheKey").toString();
        }
        List> list = new ArrayList>();
        list = redisTemplate.opsForList().range(key,0,-1);
        //     
        long cacheSize = redisTemplate.opsForList().size(key);
        if (cacheSize>0) {
            return list;
        }
        //    list   
        if(isSql==0){
        	list = sysdao.getList(map);
        }else if(isSql==1){
        	list = sysdao.getListBySql(map);
        }
        
        if(list !=null && list.size()>0){
        	//     
            redisTemplate.opsForList().leftPushAll(key,list);
            //        
            redisTemplate.expire(key, RedisTime.EXPIRETIME, TimeUnit.SECONDS);
        }
        
		return list;
	}

5.RedisTemplate操作HASH
/**
	 * redis   MAP    
	 * @param map
	 * @param isSql  1.  sql 0.   sql
	 * @return
	 */
	public Map doRedisMap(Map map,int isSql){
		
	    //       key    
        String key = "";
        if(map.get("cacheKey")!=null){
        	key = map.get("cacheKey").toString();
        }
        Map newmap = new HashMap();
        
        newmap = redisTemplate.opsForHash().entries(key);
        //     
        long cacheSize = redisTemplate.opsForHash().size(key);
        if (cacheSize>0) {
            return newmap;
        }
        //    list   
        if(isSql==0){
        	newmap = sysdao.getMapById(map);
        }else if(isSql==1){
        	newmap = sysdao.getMapBySql(map);
        }
        
        if(newmap !=null && newmap.size()>0){
        	//     
            redisTemplate.opsForHash().putAll(key,newmap);
            //        
            redisTemplate.expire(key, RedisTime.EXPIRETIME, TimeUnit.SECONDS);
        }
        
		return newmap;
	}

6.RedisTemplateキャッシュの削除
/**
	 * redis        
	 *                、        
	 * @param map 
	 * @return
	 */
	public void doRedisDelete(Map map){
		
	//       key    
	String key = "";  //  key
	String keys = ""; //   key   
        if(map.get("cacheKey")!=null){
        	key = map.get("cacheKey").toString();
        	String[] keyArr = key.split("_");
        	keys = keyArr[0]+"_List";
        }
        
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            	redisTemplate.delete(key);
        }
        
        //       key
        Set keySet = redisTemplate.keys(keys + "*");
        redisTemplate.delete(keySet);
	}

7.キャッシュされたkeyの名前の問題に注意し、単一の情報を更新および削除する場合は、親レベルのすべてのキャッシュを削除する必要があります.
8.stringタイプ以外の値を格納すると、xACxEDx 00x 05 tx 00x 0が表示される場合があります.値取りデータには影響しません.
9.参考
SpringでRedisTemplate操作Redis(spring-data-redis)を使用する
 https://www.cnblogs.com/EasonJim/p/7803067.html#autoid-2-6-0