spring boot 整合 redis

mac2024-01-29  39

一、简介

Redis 是一个使用C 语言编写的基于内存的NoSQL 数据库,是目前最流行的键值对数据库。Redis 由key、value 映射的字典构成,Redis 中的value 的类型支持字符串、列表、集合、有序集合、散列等。目前支持2种持久化方式:快照持久化和AOF 持久化,Redis 也可以搭建集群或主从复制结构。

二、流程

spring boot 对redis 提供了自动配置方案,新建spring boot Web 项目

1.pom.xml 添加如下依赖:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>

默认情况redis 使用 Lettue 工具,有的开发者习惯使用 Jedis, 可从spring-boot-starter-data-redis 中排除Lettue 并引入Jedis

2.application.yml 配置Redis

spring: redis: host: 192.168.243.133

更多配置可参考 org.springframework.boot.autoconfigure.data.redis.RedisProperties 做相关配置

3.User.java

package com.vincent; import java.io.Serializable; public class User implements Serializable{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } }

4.UserController.java

package com.vincent; import java.time.Duration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private RedisTemplate redisTemplate; @GetMapping("/getUser") public User userInfo() { return (User)redisTemplate.opsForValue().get("user"); } @GetMapping("/saveUser") public User saveUser() { User user = new User(); user.setAge(27); user.setName("你好redis"); redisTemplate.opsForValue().set("user", user, Duration.ofMinutes(2)); return user; } }

三、测试

1.访问 http://localhost:8080/saveUser

2.访问 http://localhost:8080/getUser

3./saveUser 设置了User 对象存活时间 2分钟,过期后将没有User 对象

四、总结

1.spring boot 对redis 操作提供了RedisTemplate、StringRedisTemplate

2.保存到redis 中的对象需要实现Serializable接口,否者会出现序列化失败

最新回复(0)