redis在spring boot项目开发中是常用的缓存套件,常见使用的是spring-boot-starter-data-redis
初始化spring boot项目之后,引入redis依赖
1 2 3 4 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> |
生命redis静态变量主要是为了将redis注入到spring容器当中
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Component public class redisUtils {
@Resource private RedisTemplate<String, String> redisTemplate;
public static RedisTemplate redis;
@PostConstruct public void redisUtils(){ redis = this.redisTemplate; } } |
通过set方法将需要存的数据存入到redis当中,set方法接受参数(key, value);
1 2 3 4 5 |
public String saveUser() { redisUtils.redis.opsForValue().set("name","zhangsan1"); String str = new String("保存成功"); return str; } |
使用redis读取数据,通过get方法,参数是键名,当读取的键名不存在时,返回相关信息
1 2 3 4 5 6 7 8 |
public String getUser() { Object object = redisUtils.redis.opsForValue().get("name"); if(object != null){ return object.toString(); }else{ return "数据不存在"; } } |
这里我们编写两个接口save和read,模拟接口请求的方式,从接口去读取redis缓存的数据
1 2 3 4 5 6 7 8 9 10 11 12 |
@RequestMapping("/save") public String save(){ UserService userService = new UserService(); String res = userService.saveUser(); return res; } @RequestMapping("/read") public String read(){ UserService userService = new UserService(); String res = userService.getUser(); return res; } |
redis在存取值得时候,需要注意redis的数据类型。
以上就是spring boot集成redis的基础实例,redis数据删除,以及复杂类型操作,包括其他较为深入的功能请查看
更多redis相关文档请查看 redis官方文档
项目源码地址:
https://gitee.com/lewyon/spring-note