使用Spring Boot整合Redis操作缓存
1.配置实体类–省略
2.配置mapper–省略
3.配置service–省略
以上三步可参考:
下来操作SpringBoot整合Redis
首先Redis是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库,缓存和消息中间件
1)使用docker安装redis
如果没有安装Redis, 请使用以下命令安装:
[root@localhost ~]# docker pull /library/redis如果没有安装虚拟机, 请参考:
如果虚拟机上没有安装docker, 请参考:
2)引入redis的starter
导入redis驱动包spring-boot-starter-data-redis
在pom.xml配置文件中配置如下参数:
<!--导入redis驱动包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>3)配置redis,在application.properties配置文件中配置Redis的地址, 使用如下命令:

值为虚拟机的ip
4.配置自定义的RedisTemplate序列化规则
@Configuration
public class MyRedisConfig {
/**
* 自定义转换序列化,如果使用默认保存对象序列化,则在redis中保存的数据显示的是机器码
* @param redisConnectionFactory
* @return
* @throws UnknownHostException
*/
@Bean
public RedisTemplate<Object, Employee> empredisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Employee> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(ser);
return template;
}
}5.配置测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot01CacheApplicationTests {
@Autowired
EmployeeMapper employeeMapper;
//引入redis驱动包后,就有了RedisConfiguration类以下两个类是这个类中的
//StringRedisTemplate类是操作k-v都是字符串的
@Autowired
StringRedisTemplate stringRedisTemplate;
//RedisTemplate类是操作k-v都是对象的
@Autowired
RedisTemplate redisTemplate;
//使用配置的自定义方法转换序列化,如果使用默认保存对象序列化,则在redis中保存的数据显示的是机器码
@Autowired
RedisTemplate<Object, Employee> empredisTemplate;
/**
* Redis常见的五大数据类型
* String(字符串),List(列表),Set(集合),Hash(散列),Zset(有序集合)
* stringRedisTemplate.opsForValue() 是来操作String(字符串的)的
* stringRedisTemplate.opsForList() 是来操作List(列表)的
* stringRedisTemplate.opsForSet() 是来操作Set(集合)的
* stringRedisTemplate.opsForHash() 是来操作Hash(散列)的
* stringRedisTemplate.opsForZSet() 是来操作Zset(有序集合)的
* StringRedisTemplate和RedisTemplate操作的方法是一模一样的, 只是一个操作字符串的一个操作对象的
*/
@Test
public void test01() {
//给redis添加了一个key键msg值为hello
//stringRedisTemplate.opsForValue().append("msg","hello");
//读取redis中的数据
/*String msg = stringRedisTemplate.opsForValue().get("msg");
System.out.println(msg);*/
//操作List
stringRedisTemplate.opsForList().leftPush("mylist", "1");
stringRedisTemplate.opsForList().leftPush("mylist", "2");
}
/**
* 操作对象
* 在操作对象之前,实体类必须实现序列化
*/
@Test
public void test02() {
Employee employee = employeeMapper.getEmpById(1);
//默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中
/* redisTemplate.opsForValue().set("emp-01",employee);*/
//1.将数据以json方式保存
// 1)自己将对象转为json
// 2)redisTemplate默认的序列化规则,改变默认的序列化规则
//使用配置的自定义方法转换序列化,如果使用默认保存对象序列化,则在redis中保存的数据显示的是机器码
empredisTemplate.opsForValue().set("emp-01", employee);
}
















