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

配置文件中配置redis

spring.redis.host=127.0.0.1

导入jar

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

 

 

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<Object, Employee> empRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        template.setDefaultSerializer(ser);
        return template;
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值