整合测试
说明:在SpringBoot2.x 之后,原来使用的jedis 被替换为了lettuce ?
测试连接
@Test
void contextLoads() {
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
System.out.println(connection.ping());
redisTemplate.opsForValue().set("name","bzm");
System.out.println(redisTemplate.opsForValue().get("name"));
}
真实开发,一般使用json 来传递对象
创建User对象
@Component
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User implements Serializable {
private String name;
private int age;
}
测试
@Test
void test() throws JsonProcessingException {
User user = new User("Bzm", 18);
String jsonUser = new ObjectMapper().writeValueAsString(user);
redisTemplate.opsForValue().set("user",jsonUser);
}
{“name”:“Bzm”,“age”:18}
@Test
void test() throws JsonProcessingException {
User user = new User("Bzm", 18);
redisTemplate.opsForValue().set("user",user);
System.out.println(redisTemplate.opsForValue().get("user"));
}
User(name=Bzm, age=18)
序列化
@Bean
@SuppressWarnings("all")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility .ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template. setKeySerializer(stringRedisSerializer);
template. setHashKeySerializer( stringRedisSerializer) ;
template. setValueSerializer(jackson2JsonRedisSerializer);
template. setHashValueSerializer(jackson2JsonRedisSerializer) ;
template.afterPropertiesSet();
return template;
}
测试
|