ityouknow / blog-comments

15 stars 0 forks source link

springboot(三):Spring boot中Redis的使用 - 纯洁的微笑博客 #154

Open ityouknow opened 6 years ago

ityouknow commented 6 years ago

http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html

spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化。

xweiba commented 6 years ago

大佬, redis的示例在1.5.6及以上有点问题

Spring Boot 1.4 以上 2.0 以下使用 maven spring-boot-starter-redis 依赖需要手动定义依赖版本, 如1.5.6 的spring Boot....

Spring Boot 2.0 的 spring-boot-starter-redis 改名为了 spring-boot-starter-data-redis, 而且没有 RedisCacheManager(RedisOperations redisOperations) 这个构造函数了.

<!-- Spring Boot使用的是1.4(包括1.4版本)之前的版本使用如下配置 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<!-- 1.5.* 的版本需要指定版本号 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-redis</artifactId>
   <version>1.4.6.RELEASE</version>
</dependency>
<!-- 2.* 版本 redis依赖改名了,直接使用下面的依赖 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
li1292833534 commented 6 years ago

RedisCacheManager rcm = new RedisCacheManager(redisTemplate); 发现没有一个参数的构造。。 是引入依赖错误了吗?

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

springboot 是2.0版本的 求大神帮助 卡在这里了

yueyunqing commented 6 years ago

@li1292833534 RedisCacheManager rcm = new RedisCacheManager(redisTemplate); 发现没有一个参数的构造。。 是引入依赖错误了吗?

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

springboot 是2.0版本的 求大神帮助 卡在这里了

我也是这里,有人说是Springboot2.0以后就没有 @SuppressWarnings("rawtypes") @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { 这个方法了,不知道怎么解决

zhangyuanchina commented 6 years ago

@yueyunqing public CacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheManager cacheManager = RedisCacheManager.create(factory); return cacheManager; } 采用RedisConnectionFactory 来作为构造参数

whatalittlebear commented 6 years ago

Failed to bind properties under 'spring.redis.timeout' to java.time.Duration,有人遇到吗?

whatalittlebear commented 6 years ago

我最近跑这个代码,遇到的问题总结: 1、按照大佬的方式,导入pom依赖出错: 改成:

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

这个就好了。 2、按照大佬的方式导入配置文件,出现Failed to bind properties under 'spring.redis.timeout' to java.time.Duration:这个错误,让我很是挠头。 改成:后来仔细发现我复制的,spring.redis.timeout=0后面出现个空格,我给删了,变好了。。 此外我将这个值改成5000,要不以后跑程序出错,可以先不改,如果不出现连接关闭的异常。。 3、导入大佬的代码,这段代码出问题 public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); //设置缓存过期时间 //rcm.setDefaultExpiration(60);//秒 return rcm; }我感觉是这个方法在以后的版本变化了,后来我按照其他小伙伴的方式,变成 public CacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheManager cacheManager = RedisCacheManager.create(factory); return cacheManager; }虽说是编译不出问题,但是运行出了问题,所以我直接注释了,就好了,还没发现什么不妥 如果有坑,以后再碰吧,^_^

linvil commented 6 years ago

@li1292833534 RedisCacheManager rcm = new RedisCacheManager(redisTemplate); 发现没有一个参数的构造。。 是引入依赖错误了吗?

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

springboot 是2.0版本的 求大神帮助 卡在这里了

@xweiba 大佬, redis的示例在1.5.6及以上有点问题

Spring Boot 1.4 以上 2.0 以下使用 maven spring-boot-starter-redis 依赖需要手动定义依赖版本, 如1.5.6 的spring Boot....

Spring Boot 2.0 的 spring-boot-starter-redis 改名为了 spring-boot-starter-data-redis, 而且没有 RedisCacheManager(RedisOperations redisOperations) 这个构造函数了.

<!-- Spring Boot使用的是1.4(包括1.4版本)之前的版本使用如下配置 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<!-- 1.5.* 的版本需要指定版本号 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-redis</artifactId>
   <version>1.4.6.RELEASE</version>
</dependency>
<!-- 2.* 版本 redis依赖改名了,直接使用下面的依赖 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

@yueyunqing

@li1292833534 RedisCacheManager rcm = new RedisCacheManager(redisTemplate); 发现没有一个参数的构造。。 是引入依赖错误了吗?

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

springboot 是2.0版本的 求大神帮助 卡在这里了

我也是这里,有人说是Springboot2.0以后就没有 @SuppressWarnings("rawtypes") @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { 这个方法了,不知道怎么解决

springboot2.0没有不带参数的构造了,可以这样: @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { //设置缓存过期时间 RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1));

    return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
            .cacheDefaults(redisCacheConfiguration).build();
}
maogy9527 commented 6 years ago

我什么我根据就无法引入RedisCacheManager这个类,写出来下面有红色的波浪线,没有import这个类的选项

Georgeqhh commented 6 years ago

能弄个 目录吗

gepengjun commented 6 years ago

大神,使用注解模式使用redis,当查找的是关联对象时,要怎么处理?

java-aodeng commented 6 years ago

Springboot2配置的时候有点不同了,这是springboot2.0配置的代码


@Bean
    CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        //user信息缓存配置
        RedisCacheConfiguration userCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(30)).disableCachingNullValues().prefixKeysWith("role");
        //product信息缓存配置
        RedisCacheConfiguration productCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)).disableCachingNullValues().prefixKeysWith("test");
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
        redisCacheConfigurationMap.put("role", userCacheConfiguration);
        redisCacheConfigurationMap.put("test", productCacheConfiguration);
        //初始化一个RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
        //设置CacheManager的值序列化方式为JdkSerializationRedisSerializer,但其实RedisCacheConfiguration默认就是使用StringRedisSerializer序列化key,JdkSerializationRedisSerializer序列化value,所以以下注释代码为默认实现
        //ClassLoader loader = this.getClass().getClassLoader();
        //JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(loader);
        //RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jdkSerializer);
        //RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);

        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
        //设置默认超过期时间是30秒
        defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
        //初始化RedisCacheManager
        RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig, redisCacheConfigurationMap);
        return cacheManager;
    }
skyfinging commented 6 years ago

@CacthNewBug 我什么我根据就无法引入RedisCacheManager这个类,写出来下面有红色的波浪线,没有import这个类的选项

这个类在import org.springframework.data.redis.cache.RedisCacheManager;手动引入试试吧

KeenKey commented 5 years ago

现在springBoot都演进到了2.0版本,楼主提供的代码在2.0上跑不起来。总结了下,有几个问题: 【1】 2.0版本引入redis依赖时应使用spring-boot-starter-data-redis代替spring-boot-starter-redis。 【2】 pom中引入支持热启动的spring-boot-devtools依赖包时,在将redis中持久化的对象取出并进行反序列化时出现“ClassCastException”,因此要注掉这个依赖。具体原因参见https://www.jianshu.com/p/e6d5a3969343。 【3】 RedisConfig的代码要进行改造。 @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport {

@Bean
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
        @Override
        public Object generate(Object target, Method method, Object... params) {
            // TODO Auto-generated method stub
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            return sb.toString();
        }

    };
}

@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    //设置缓存过期时间
    RedisCacheConfiguration redisCacheCfg=RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1));
    return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                            .cacheDefaults(redisCacheCfg)
                            .build();
}

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

} 【4】 使用@Cacheable注解生成redis缓存时,需要指定keyGenerator参数: @RestController public class UserController {

@Autowired
private UserRepository userRepository;

@RequestMapping("/getUser")
@Cacheable(value="user-key", keyGenerator="keyGenerator")
public User getUser(String userName) {
    User user = userRepository.findByUserName(userName);
    System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");  
    return user;
}   

}

maogy9527 commented 5 years ago

嗯额,谢谢

在 2019-01-20 13:24:24,"KeenKey" notifications@github.com 写道:

现在springBoot都演进到了2.0版本,楼主提供的代码在2.0上跑不起来。总结了下,有几个问题: 【1】 2.0版本引入redis依赖时应使用spring-boot-starter-data-redis代替spring-boot-starter-redis。 【2】 pom中引入支持热启动的spring-boot-devtools依赖包时,在将redis中持久化的对象取出并进行反序列化时出现“ClassCastException”,因此要注掉这个依赖。具体原因参见https://www.jianshu.com/p/e6d5a3969343。 【3】 RedisConfig的代码要进行改造。 @configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport {

@Bean

public KeyGenerator keyGenerator() {

return new KeyGenerator() {

    @Override

    public Object generate(Object target, Method method, Object... params) {

        // TODO Auto-generated method stub

        StringBuilder sb = new StringBuilder();

        sb.append(target.getClass().getName());

        sb.append(method.getName());

        return sb.toString();

    }

};

}

@Bean

public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {

//设置缓存过期时间

RedisCacheConfiguration redisCacheCfg=RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1));

return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))

                        .cacheDefaults(redisCacheCfg)

                        .build();

}

@Bean

public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory factory){

StringRedisTemplate template = new StringRedisTemplate(factory);

Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

//GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(Object.class);

ObjectMapper om = new ObjectMapper();

om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

om.enableDefaultTyping();

jackson2JsonRedisSerializer.setObjectMapper(om);

template.setValueSerializer(jackson2JsonRedisSerializer);

template.afterPropertiesSet();

return template;

}

} 【4】 使用@Cacheable注解生成redis缓存时,需要指定keyGenerator参数: @RestController public class UserController {

@Autowired

private UserRepository userRepository;

@RequestMapping("/getUser")

@Cacheable(value="user-key", keyGenerator="keyGenerator")

public User getUser(String userName) {

User user = userRepository.findByUserName(userName);

System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");  

return user;

}

}

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub, or mute the thread.

ityouknow commented 5 years ago

课程内容已经升级到 2.X 版本了。

niuniu201010 commented 5 years ago

连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1

spring.redis.lettuce.pool.max-wait=-1

需要增加时间单位ms?

Strong-Man commented 5 years ago

@ityouknow 课程内容已经升级到 2.X 版本了。

Strong-Man commented 5 years ago

Caused by: java.lang.ClassNotFoundException: org.springframework.security.web.authentication.RememberMeServices 有同志遇见过这个问题吗?我springboot版本是2.1.5.RELEASE

maxlange commented 5 years ago

@Strong-Man Caused by: java.lang.ClassNotFoundException: org.springframework.security.web.authentication.RememberMeServices 有同志遇见过这个问题吗?我springboot版本是2.1.5.RELEAS 缺包吧,security的依赖没导进来?

iMLe0n commented 5 years ago

@Strong-Man Caused by: java.lang.ClassNotFoundException: org.springframework.security.web.authentication.RememberMeServices 有同志遇见过这个问题吗?我springboot版本是2.1.5.RELEASE

pom文件添加以下

  <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.security</groupId>
                    <artifactId>spring-security-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
Strong-Man commented 5 years ago

@iMLe0n

@Strong-Man Caused by: java.lang.ClassNotFoundException: org.springframework.security.web.authentication.RememberMeServices 有同志遇见过这个问题吗?我springboot版本是2.1.5.RELEASE

pom文件添加以下

  <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.security</groupId>
                    <artifactId>spring-security-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

好的 谢谢 我今天试试

Strong-Man commented 5 years ago

@maxlange

@Strong-Man Caused by: java.lang.ClassNotFoundException: org.springframework.security.web.authentication.RememberMeServices 有同志遇见过这个问题吗?我springboot版本是2.1.5.RELEAS 缺包吧,security的依赖没导进来?

好的 谢谢 我今天试试!感谢感谢

churchillyik commented 5 years ago

spring boot 2.1.5,我是加了

org.springframework.security spring-security-web

才能运行过的

GTUUABT commented 5 years ago

org.springframework.security.web.authentication.RememberMeServices,我也是一直报这个错,开始以为是jar包冲突,用maven Helper又没发现冲突,后来将springBoot的版本降到了2.0.0,后来就可以了!

ZhenhaoLu commented 5 years ago

大佬我的程序里redisTemplate放进缓存的Object用@Cacheable提不出来,好像是反序列化的算法不同,这是因为这两个类所属的包的版本差异还是从一开始这两个的算法就不同?

jj89757hhb commented 5 years ago

这个要先搭建好Redis吗?

misaya98 commented 5 years ago

emm 可以在末尾加个下一篇的链接 每次看完一篇都得返回找下一篇

lhkxiaowang commented 5 years ago

哎 初学好多看不懂, 一篇文章需要消化好几天。

XiaoFengSophia commented 5 years ago

笑哥,你获取session的时候是不是少了一个方法的返回值啊!

maogy9527 commented 5 years ago

现在springBoot都演进到了2.0版本,楼主提供的代码在2.0上跑不起来。总结了下,有几个问题: 【1】 2.0版本引入redis依赖时应使用spring-boot-starter-data-redis代替spring-boot-starter-redis。 【2】 pom中引入支持热启动的spring-boot-devtools依赖包时,在将redis中持久化的对象取出并进行反序列化时出现“ClassCastException”,因此要注掉这个依赖。具体原因参见https://www.jianshu.com/p/e6d5a3969343。 【3】 RedisConfig的代码要进行改造。 @configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport {

@Bean
public KeyGenerator keyGenerator() {
  return new KeyGenerator() {
      @Override
      public Object generate(Object target, Method method, Object... params) {
          // TODO Auto-generated method stub
          StringBuilder sb = new StringBuilder();
          sb.append(target.getClass().getName());
          sb.append(method.getName());
          return sb.toString();
      }

  };
}

@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
  //设置缓存过期时间
  RedisCacheConfiguration redisCacheCfg=RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1));
  return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                          .cacheDefaults(redisCacheCfg)
                          .build();
}

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

} 【4】 使用@Cacheable注解生成redis缓存时,需要指定keyGenerator参数: @RestController public class UserController {

@Autowired
private UserRepository userRepository;

@RequestMapping("/getUser")
@Cacheable(value="user-key", keyGenerator="keyGenerator")
public User getUser(String userName) {
  User user = userRepository.findByUserName(userName);
  System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");  
    return user;
} 

}

大佬现在这里有个问题想请教一下,现在我配置一个与RedisTemplate的配置类和在里面写了如下方法,打算让实体类存入到Redis中时,进行序列化处理,但是在用单元测试时注入stuRedisTemplate该配置方法时一个报这个错误;想请教一下是什么原因。异常即方法代码写下面 1.Config配置类 @Configuration public class MyRedisConfig extends CachingConfigurerSupport{

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

} 2.实体类,get,set方法就不复制上来了 public class Student implements Serializable{

private Integer autoId;
private Integer teacherId;
private String name;
private int age;

} 3.单元测试类 @RunWith(SpringRunner.class) @SpringBootTest public class Springbootdemo19CacheApplicationTests {

@Autowired
private RedisTemplate redisTemplate;  
@Autowired
private RedisTemplate<Object,Student> stuRedisTemplate;

    /**
 * 测试保存对象到Redis
 */
@Test
public void testRedis02(){
    Student student = studentService.getStu(1);
    stuRedisTemplate.opsForValue().set("stu1",student);
}

} 4.所报的错误异常,在调用testRedis02()方法时就直接报这个错了,是不是我的config类写错了没能根据 spring boot自动进行装配?当时config类的路径也对,之前我也写过其他自定义的配置类也是没有问题的 现在的报这个错误找了很久找不到原因。望大佬指教 2019-07-21 14:12:03.285 ERROR 7088 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@43195e57] to prepare test instance [com.mao.Springbootdemo19CacheApplicationTests@550de6b8]

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.mao.Springbootdemo19CacheApplicationTests': Unsatisfied dependency expressed through field 'stuRedisTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<java.lang.Object, com.mao.entity.Student>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:391) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43) ~[spring-boot-test-autoconfigure-2.1.6.RELEASE.jar:2.1.6.RELEASE] at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12] at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12] at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na] at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) [junit-rt.jar:na] at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na] at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na] Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<java.lang.Object, com.mao.entity.Student>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1658) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1217) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] ... 28 common frames omitted

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.mao.Springbootdemo19CacheApplicationTests': Unsatisfied dependency expressed through field 'stuRedisTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<java.lang.Object, com.mao.entity.Student>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:391)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<java.lang.Object, com.mao.entity.Student>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1658) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1217) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ... 28 more

2019-07-21 14:12:03.330 INFO 7088 --- [ Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

Process finished with exit code -1

qq1012405911 commented 5 years ago

nice

bart233 commented 5 years ago

如果我updateUser的话怎么删除生成的缓存啊

2578197547 commented 5 years ago

@CachePut和@CacheEvict

------------------ 原始邮件 ------------------ 发件人: "bart233"notifications@github.com; 发送时间: 2019年7月24日(星期三) 下午5:26 收件人: "ityouknow/blog-comments"blog-comments@noreply.github.com; 抄送: "谢丽杰"764682881@qq.com;"Comment"comment@noreply.github.com; 主题: Re: [ityouknow/blog-comments] springboot(三):Spring boot中Redis的使用 - 纯洁的微笑博客 (#154)

如果我updateUser的话怎么删除生成的缓存啊

— You are receiving this because you commented. Reply to this email directly, view it on GitHub, or mute the thread.

maogy9527 commented 5 years ago

现在springBoot都演进到了2.0版本,楼主提供的代码在2.0上跑不起来。总结了下,有几个问题: 【1】 2.0版本引入redis依赖时应使用spring-boot-starter-data-redis代替spring-boot-starter-redis。 【2】 pom中引入支持热启动的spring-boot-devtools依赖包时,在将redis中持久化的对象取出并进行反序列化时出现“ClassCastException”,因此要注掉这个依赖。具体原因参见https://www.jianshu.com/p/e6d5a3969343。 【3】 RedisConfig的代码要进行改造。 @configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport {

@Bean
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
        @Override
        public Object generate(Object target, Method method, Object... params) {
            // TODO Auto-generated method stub
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            return sb.toString();
        }

    };
}

@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    //设置缓存过期时间
    RedisCacheConfiguration redisCacheCfg=RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1));
    return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                            .cacheDefaults(redisCacheCfg)
                            .build();
}

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

} 【4】 使用@Cacheable注解生成redis缓存时,需要指定keyGenerator参数: @RestController public class UserController {

@Autowired
private UserRepository userRepository;

@RequestMapping("/getUser")
@Cacheable(value="user-key", keyGenerator="keyGenerator")
public User getUser(String userName) {
    User user = userRepository.findByUserName(userName);
    System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");  
    return user;
}   

}

大佬现在这里有个问题想请教一下,现在我配置一个与RedisTemplate的配置类和在里面写了如下方法,打算让实体类存入到Redis中时,进行序列化处理,但是在用单元测试时注入stuRedisTemplate该配置方法时一个报这个错误;想请教一下是什么原因。异常即方法代码写下面 1.Config配置类 @configuration public class MyRedisConfig extends CachingConfigurerSupport{

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

} 2.实体类,get,set方法就不复制上来了 public class Student implements Serializable{

private Integer autoId;
private Integer teacherId;
private String name;
private int age;

} 3.单元测试类 @RunWith(SpringRunner.class) @SpringBootTest public class Springbootdemo19CacheApplicationTests {

@Autowired
private RedisTemplate redisTemplate;  
@Autowired
private RedisTemplate<Object,Student> stuRedisTemplate;

    /**
 * 测试保存对象到Redis
 */
@Test
public void testRedis02(){
  Student student = studentService.getStu(1);
  stuRedisTemplate.opsForValue().set("stu1",student);
}

} 4.所报的错误异常,在调用testRedis02()方法时就直接报这个错了,是不是我的config类写错了没能根据 spring boot自动进行装配?当时config类的路径也对,之前我也写过其他自定义的配置类也是没有问题的 现在的报这个错误找了很久找不到原因。望大佬指教 2019-07-21 14:12:03.285 ERROR 7088 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@43195e57] to prepare test instance [com.mao.Springbootdemo19CacheApplicationTests@550de6b8]

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.mao.Springbootdemo19CacheApplicationTests': Unsatisfied dependency expressed through field 'stuRedisTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<java.lang.Object, com.mao.entity.Student>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:391) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43) ~[spring-boot-test-autoconfigure-2.1.6.RELEASE.jar:2.1.6.RELEASE] at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) ~[spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12] at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12] at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na] at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) [junit-rt.jar:na] at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na] at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na] Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<java.lang.Object, com.mao.entity.Student>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1658) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1217) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] ... 28 common frames omitted

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.mao.Springbootdemo19CacheApplicationTests': Unsatisfied dependency expressed through field 'stuRedisTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<java.lang.Object, com.mao.entity.Student>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:391)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<java.lang.Object, com.mao.entity.Student>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1658) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1217) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ... 28 more

2019-07-21 14:12:03.330 INFO 7088 --- [ Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

Process finished with exit code -1

今日周末有空又重新去弄的今天这个问题,重新建了一个新工程B把代码旧工程A的代码全部拷过去运行一遍竟然跑通了,而且序列化对象也成功写入Redis中。但是一样的代码在旧工程A中依旧无法跑通。但旧工程A中的MyRedisConfig配置类中,路径下的类名小图标上有一个灰色的小小的×,这次我把MyRedisConfig删掉重新复制回去,小X就消失。项目跑起来打断点成功进入了该配置类,接着后续流程正常了。但是上周我也试过删除MyRedisConfig配置类依旧无效果,小X当时依旧存在。这周删掉后重新弄进来就OK了,修复原因不明.............(允许我做个悲伤的表情)