SpringBoot中使用Redis保存对象

1、引入依赖

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

2、配置主机

spring.redis.host=192.168.124.15

3、查看源码
在这里插入图片描述
4、配置类

@Configuration
public class MyRedisConfig {
	@Bean
	public RedisTemplate<Object, Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory)
			throws UnknownHostException {
		RedisTemplate<Object, Employee> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		Jackson2JsonRedisSerializer<Employee> serializer = new Jackson2JsonRedisSerializer<>(Employee.class);
		template.setDefaultSerializer(serializer);
		return template;
	}
}

5、测试

@Autowired
RedisTemplate redisTemplate;
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
RedisTemplate<Object, Employee> empRedisTemplate;
@Test
public void test01(){
	stringRedisTemplate.opsForValue().set("msg","hello");
	String msg = stringRedisTemplate.opsForValue().get("msg");
	System.out.println(msg);
	stringRedisTemplate.opsForList().leftPushAll("mylist","1","2");
}
@Test
public void test02() {
	Employee employee = new Employee(1,"张三",18);
	redisTemplate.opsForValue().set("emp",employee);
	empRedisTemplate.opsForValue().set("emp",employee);
}

6、测试结果
在这里插入图片描述

©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页