springboot整合本机redis测试出错

springboot整合本机redis测试出错

我用docker启动的redis服务端。redis-cli连接服务端并进行测试。

img



img



可以看到本机的redis服务算是正常启动并成功配置在了6379端口。
我的springboot项目结构为:

img



其中application.yml如下:

img

SpringbootRedisApplicationTests.java如下:

img

我只运行测试了其中的testSet方法,报错如下:

img

img

请问该如何解决呢?

Redis有配置密码吗

【以下回答由 GPT 生成】

问题原因:报错提示找不到类型为StringRedisTemplate的bean,即没有注入该bean。

解决方法:在Spring Boot的测试环境中,需要手动配置Redis相关的bean,以便在测试中使用。可以通过创建一个配置类,在其中配置StringRedisTemplate的bean。下面是具体的解决方案:

1.在com.example包下创建一个新的配置类,命名为RedisConfig,并添加@Configuration注解,表示这是一个配置类。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration
public class RedisConfig {

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }
}

2.需要在SpringbootRedisApplicationTests测试类的上方加上@Import注解,引入刚刚创建的配置类。

@RunWith(SpringRunner.class)
@SpringBootTest
@Import(RedisConfig.class)
public class SpringbootRedisApplicationTests {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Test
    public void testSet() {
        redisTemplate.opsForValue().set("key", "value");
        String result = redisTemplate.opsForValue().get("key");
        assertEquals("value", result);
    }
}

3.重新运行testSet方法进行测试,此时应该就可以正常执行了。

这样就解决了报错找不到StringRedisTemplate的问题。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

你这是无法连接Redis服务,猜测还是你docker没有实现内部网络互相通信导致的,建议如果自己玩,也可以搭建个Windows版本的Redis服务。这里给你推荐一篇我的写的: