我用docker启动的redis服务端。redis-cli连接服务端并进行测试。
可以看到本机的redis服务算是正常启动并成功配置在了6379端口。
我的springboot项目结构为:
其中application.yml如下:
SpringbootRedisApplicationTests.java如下:
我只运行测试了其中的testSet方法,报错如下:
请问该如何解决呢?
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服务。这里给你推荐一篇我的写的: