Springboot下redis使用及以json方式缓存方法

配置文件中配置redis

spring.redis.host=127.0.0.1

导入jar


			org.springframework.boot
			spring-boot-starter-data-redis
		

 

 

estringRedisTemplate;   操作k-v都是字符串的

 

eredisTemplate          k-v都是对象

 

 

Redis常见的五大数据类型

String(字符串)、List(列表)、Set(集合)、Hash(散列)、ZSet(有序集合)

stringRedisTemplate.opsForValue()[String(字符串)]

stringRedisTemplate.opsForList()[List(列表)]

stringRedisTemplate.opsForSet()[Set(集合)]

stringRedisTemplate.opsForHash()[Hash(散列)]

stringRedisTemplate.opsForZSet()[ZSet(有序集合)]

 

@Test

publicvoidtest01(){

//给redis中保存数据

//stringRedisTemplate.opsForValue().append("msg","hello");

//Stringmsg=stringRedisTemplate.opsForValue().get("msg");

//System.out.println(msg);

 

//stringRedisTemplate.opsForList().leftPush("mylist","1");

//stringRedisTemplate.opsForList().leftPush("mylist","2");

}

 

//测试保存对象

@Test

publicvoidtest02(){

EmployeeempById=employeeMapper.getEmpById(1);

//默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中

//redisTemplate.opsForValue().set("emp-01",empById);

//1、将数据以json的方式保存

//(1)自己将对象转为json

//(2)redisTemplate默认的序列化规则;改变默认的序列化规则

empRedisTemplate.opsForValue().set("emp-01",empById);}

 

redisTemplate默认的序列化规则;改变默认的序列化规则

@Configuration
public class MyRedisConfig {

    @Bean
    public RedisTemplate empRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer ser = new Jackson2JsonRedisSerializer(Employee.class);
        template.setDefaultSerializer(ser);
        return template;
    }

 

你可能感兴趣的:(springboot)