Redis整合SpringBoot

整合测试

说明:在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
//在企业中所有的pojo对象都会序列化
public class User implements Serializable {
    private String name;
    private int age;
}

测试

@Test
    void test() throws JsonProcessingException {
        //真实开发,一般使用json来传递对象
        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 {
        //真实开发,一般使用json来传递对象
        User user = new User("Bzm", 18);
//        String jsonUser = new ObjectMapper().writeValueAsString(user);
        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);

        //Json序列化配置
        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);

        //String 序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        //key采用string的序列化方式
        template. setKeySerializer(stringRedisSerializer);
        //hash的key也采用string的序列化方式
        template. setHashKeySerializer( stringRedisSerializer) ;
        //value序列化方式采用jackson .
        template. setValueSerializer(jackson2JsonRedisSerializer);
        //hash的value序列化方式采用jackson
        template. setHashValueSerializer(jackson2JsonRedisSerializer) ;
        template.afterPropertiesSet();

        return template;
    }

测试

在这里插入图片描述

你可能感兴趣的:(JAVA,Redis,java,redis)