Redis的连接需要准备以下三步:
第一步 : 导入pom依赖或者看一下有没有下面的依赖 ,对于多个模块而言 ,只要有一个模块引入下面的依赖 ,所有模块会通用pom中的依赖
第二步 : yml配置一下 ,localhost就是127.0.0.1
第三步(选做,如果用的是StringRedisTemplate就不要写了,这个是给RedisTemplate服务的) : 编写配置类,注意@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.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){
// 创建RedisTemplate对象
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 设置连接工厂
template.setConnectionFactory(connectionFactory);
// 创建JSON序列化工具
GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
// 设置Key的序列化
template.setKeySerializer(RedisSerializer.string());
template.setHashKeySerializer(RedisSerializer.string());
// 设置Value的序列化
template.setValueSerializer(jsonRedisSerializer);
template.setHashValueSerializer(jsonRedisSerializer);
// 返回
return template;
}
}
-
RedisTemplate : 更多存的是对象
-
StringRedisTemplate : 泛型指定的是String。当存入对象时,会报错 :can not cast into String
第四步 : 测试
-
注意测试类尽量使用绿色的test包,层级要和启动类保持一致
-
注意导入以下包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
-
注意测试类上面要有@SpringBootTest注解 ,这个注解在pom中的依赖为import org.springframework.boot.test.context.SpringBootTest;
-
注意@Test注解import org.junit.jupiter.api.Test;