springboot集成reids简单示例

redis作为内存型的非关系型数据库,在项目中经常会被采用,用个小例子说明redis 的基本用法

1:在项目的pom 文件中引入 redis 的依赖

<!--springboot整合redis-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2:在 application.properties 配置 redis 的连接信息

#配置redis连接信息(单机模式)
spring.redis.host=192.168.58.128
spring.redis.port=6379
spring.redis.password=123456

3:代码中的实现

@Autowired
private RedisTemplate<Object,Object> redisTemplate;

@GetMapping("/get/{id}")
@ResponseBody
public Student getOne(@PathVariable Integer id){
     //redis序列化的方式
     RedisSerializer stringSerializer = new StringRedisSerializer();
     redisTemplate.setKeySerializer(stringSerializer);
     //首先从缓存中获取
     Student student= (Student) redisTemplate.opsForValue().get("studentSave");

     if(null!=student){
          log.info("redis方式");
          return student;
     }
     //缓冲中无数据,从数据库中获取,并放入redis保存
     log.info("mysql 方式");
     student= studentService.selectOne(id);
     //磁盘的存储要求类实现序列化(Student implements Serializable)
     redisTemplate.opsForValue().set("studentSave",student);
     return student;
}

注意:springboot 自动集成的 redis 模板对象泛型只识别RedisTemplate<Object,Object> redisTemplate; 与 RedisTemplate<String,String> redisTemplate;

发布了27 篇原创文章 · 获赞 1 · 访问量 840

猜你喜欢

转载自blog.csdn.net/weixin_44971379/article/details/105154148