redis的默认端口号为6379
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.添加到redis 里的数据为二进制需要需要序列化(转化为json格式)需要添加配置类
package com.zzq.springboot_redis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class Config {
@Bean
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//修改默认的序列化规则
//1.创建序列化规则对象
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
//2.更改默认的序列化规则
template.setDefaultSerializer(jackson2JsonRedisSerializer);
return template;
}
}
3.实体类需 implements Serializable
4.实现类
@Autowired
private RedisTemplate redisTemplate;
@Override
public List<Student> getAll() {
String key = "student";
ListOperations<String, Student> listOperations = redisTemplate.opsForList();
Boolean aBoolean = redisTemplate.hasKey(key);
if (aBoolean) {
return listOperations.range(key, 0, -1);
} else {
List<Student> all = studentMapper.getAll();
listOperations.leftPushAll(key, all);
return all;
}
5.控制层
@GetMapping("/students")
public List<Student> getAll(){
return studentServiece.getAll();
}