义齿


springboot1.5のバージョンredisクライアントのデフォルトはjedis、2.0以上のバージョンのデフォルトはlettuce
本文はlettuceを採用して、アプリケーションを.ymlプロファイルのjedisをlettuceに変更し、
一、pom.xml


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.8.RELEASE
         
    
    com.urthink.upfs
    upfs-provider
    0.0.1-SNAPSHOT
    upfs-provider
    Upfs provider project for Spring Boot

    
        1.8
        Finchley.SR2
    

    
        
        
            org.springframework.boot
            spring-boot-starter
            
                
                    org.springframework.boot
                    spring-boot-starter-logging
                
            
        

        
        
            org.springframework.boot
            spring-boot-starter-log4j2
        

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            org.apache.commons
            commons-pool2
        

        
            org.springframework.boot
            spring-boot-starter-web
        

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

        
            org.projectlombok
            lombok
            true
        

        
            com.urthink.upfs
            upfs-model
            0.0.1-SNAPSHOT
        
    

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


二、アプリケーションyml
max-waitとtimeoutは単位を書くべきで、さもなくばエラーredis timeout Value'2000'is not a valid durationを提示します
spring:
  redis:
    # Redis     (   0)
    database: 10
    # Redis     
    host: 192.168.203.220
    # Redis       
    port: 6379
    # Redis       (    )
    password:
    lettuce:
      pool:
        #         (          )
        max-active: 200
        #            
        max-idle: 20
        #            
        min-idle: 10
        #            (          )
        max-wait: -1ms
    #       (  )   2000ms
    timeout: 2000ms

三、RedisConfiguration.java
このクラスは主にいくつかの配置をして、このクラスがなくて、次の3つのテストクラスも走ることができます.
package com.urthink.upfs.provider.config;

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.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

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

/**
 * redis   
 *   :RedisAutoConfiguration
 * @author zhao
 * @date 2019.1.16
 */
@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {

    //@Autowired
    //private RedisConnectionFactory redisConnectionFactory;


    @Bean   //       Key    ,key    
    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();
            }
        };
    }

    @Bean
    public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
        //spring cache       
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getKeySerializer()))        //key     
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()))    //value     
                .disableCachingNullValues()         //   null 
                .entryTtl(Duration.ofSeconds(60));  //        

        //             set  
        Set cacheNames =  new HashSet<>();
        cacheNames.add("user");

        //               ,       
        Map configMap = new HashMap<>();
        configMap.put("user", redisCacheConfiguration.entryTtl(Duration.ofSeconds(120)));

        RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisTemplate.getConnectionFactory())
                .cacheDefaults(redisCacheConfiguration)
                .transactionAware()
                .initialCacheNames(cacheNames)  //           ,                  ,         
                .withInitialCacheConfigurations(configMap)
                .build();
        return redisCacheManager;
    }

//    @Bean
//    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
//        //         ,                 
//        //         ,  config              
//        //RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
//        //config = config.entryTtl(Duration.ofSeconds(60))    //            ,    Duration  
//        //        .disableCachingNullValues();                //      
//        //RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).cacheDefaults(config).build();
//        RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).build();
//        return redisCacheManager;
//    }


    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        //   redisTemplate
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        //     
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//      ObjectMapper om = new ObjectMapper();
//      om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); //{"id":"1","name":"  ","age":18}
////    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);   //json        //["com.urthink.upfs.model.entity.User",{"id":"1","name":"  ","age":18}]
//      jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisSerializer stringSerializer = new StringRedisSerializer();

        redisTemplate.setKeySerializer(stringSerializer);                   // key   
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);      // value   
        redisTemplate.setHashKeySerializer(stringSerializer);               // Hash key   
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);  // Hash value   
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

三、テストクラス
1.User.java
package com.urthink.upfs.model.entity;

import lombok.Data;

import java.io.Serializable;

/**
 *    
 */
@Data
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    private String id;
    private String name;
    private int age;

}

2.UserService.JAva,spring boot cache注記
package com.urthink.upfs.provider.service;

import com.urthink.upfs.model.entity.User;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Cacheable(value="user", key="#id") //user::0
    public User getUser(String id) {
        System.out.println(id+"         !");
        User user = new User();
        user.setId(id);
        user.setName("  ");
        user.setAge(18);
        return user;
    }

    @CacheEvict(value="user", key="#id", condition="#id!='1'")
    public void deleteUser(String id) {
        System.out.println(id+"         !");
    }

}

3.RedisService.JAva,redisツールクラス,不要
package com.urthink.upfs.provider.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis    
 */
@Component
public class RedisService {

    //        redisTemplate  , key(not hashKey)     String  
    private RedisTemplate redisTemplate;
    //        redisTemplate            
    private HashOperations hashOperations;
    private ListOperations listOperations;
    private ZSetOperations zSetOperations;
    private SetOperations setOperations;
    private ValueOperations valueOperations;

    // IDEA    ,          ,                    Redis   
    @Autowired
    public RedisService(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.hashOperations = redisTemplate.opsForHash();
        this.listOperations = redisTemplate.opsForList();
        this.zSetOperations = redisTemplate.opsForZSet();
        this.setOperations = redisTemplate.opsForSet();
        this.valueOperations = redisTemplate.opsForValue();
    }


    public void hashPut(String key, HK hashKey, V value) {
        hashOperations.put(key, hashKey, value);
    }

    public Map hashFindAll(String key) {
        return hashOperations.entries(key);
    }

    public V hashGet(String key, HK hashKey) {
        return hashOperations.get(key, hashKey);
    }

    public void hashRemove(String key, HK hashKey) {
        hashOperations.delete(key, hashKey);
    }

    public Long listPush(String key, V value) {
        return listOperations.rightPush(key, value);
    }

    public Long listUnshift(String key, V value) {
        return listOperations.leftPush(key, value);
    }

    public List listFindAll(String key) {
        if (!redisTemplate.hasKey(key)) {
            return null;
        }
        return listOperations.range(key, 0, listOperations.size(key));
    }

    public V listLPop(String key) {
        return listOperations.leftPop(key);
    }

    public void setValue(String key, V value) {
        valueOperations.set(key, value);
    }

    public void setValue(String key, V value, long timeout) {
        ValueOperations vo = redisTemplate.opsForValue();
        vo.set(key, value, timeout, TimeUnit.MILLISECONDS);
    }


    public V getValue(String key) {
        return valueOperations.get(key);
    }

    public void remove(String key) {
        redisTemplate.delete(key);
    }

    public boolean expire(String key, long timeout, TimeUnit timeUnit) {
        return redisTemplate.expire(key, timeout, timeUnit);
    }
}

4.RedisTemplateTest.java
StringRedisTemplate、RedisTemplate、RedisTemplateを使用してもかまいません
package com.urthink.upfs.provider;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.TimeUnit;

/**
 * redisTemplate  
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTemplateTest {

    @Autowired
    //private StringRedisTemplate redisTemplate;
    private RedisTemplate redisTemplate;
    //private RedisTemplate redisTemplate;

    @Test
    public void testRedisTemplate(){
        redisTemplate.opsForValue().set("test2","ddd",50, TimeUnit.SECONDS);
        System.out.println(redisTemplate.opsForValue().get("test2"));
    }
}

5.RedisCacheTest
package com.urthink.upfs.provider;


import com.urthink.upfs.model.entity.User;
import com.urthink.upfs.provider.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * SpringBoot      
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisCacheTest {

    @Autowired
    private StringRedisTemplate template;

    @Autowired
    private UserService userService;


    @Test
    public void getUser() {
        for (int i = 0; i < 5; i++) {
            User user = userService.getUser(String.valueOf(i));
            System.out.println(user);
        }
    }

    @Test
    public void deleteUser() {
        for (int i = 0; i < 5; i++) {
            userService.deleteUser(String.valueOf(i));
        }
    }
}

6.RedisServiceTest.java
package com.urthink.upfs.provider;

import com.urthink.upfs.provider.service.RedisService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * RedisService  
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisServiceTest {
    @Autowired
    RedisService redisService;

    @Test
    public void setTest()  {
        redisService.setValue("key","hello");
    }

    @Test
    public void getTest()  {
        System.out.println("getTest:"+ redisService.getValue("key"));
    }

}


redisのキー値user:::1{“id”:“1”,“name”:“張三”,“age”:18}
キーにはなぜ2つのコロンが付いていますか:?
RedisCacheクラスcreateCacheKeyメソッドCacheKeyPrefixインタフェース
   /**
     * Creates a default {@link CacheKeyPrefix} scheme that prefixes cache keys with {@code cacheName} followed by double
     * colons. A cache named {@code myCache} will prefix all cache keys with {@code myCache::}.
     *
     * @return the default {@link CacheKeyPrefix} scheme.
     */
    static CacheKeyPrefix simple() {
        return name -> name + "::";
    }

 
参照先:
义齿https://www.cnblogs.com/antball/p/9239663.html
SpringBoot 2.X集積Redis(Lettuce)https://blog.csdn.net/lx1309244704/article/details/80696235
SpringBoot 2統合Redisキャッシュhttps://blog.csdn.net/zsj777/article/details/80801824
SpringBoot2.0.3 Redisキャッシュ@Cacheable,@CacheEveict,@CachePuthttps://blog.csdn.net/u010588262/article/details/81003493
史上最も包括的なSpring Boot Cacheの使用と整https://www.cnblogs.com/yueshutong/p/9381540.html