首先我们先知道Redis是一个nosql,也就是说跟我们之前所学习的常规的mysql等不一样,
Redis一般来说是通过键值对的形式来存储内容,比如
key:001
value:
{
"id": 1,
"name": "zmh",
"birthday": "2005-10-13"
}
key:002
value:
{
"id": 2,
"name": "klr",
"birthday": "2004-07-22"
}
这些k-v键值对的形式来存储
首先我们需要在开始编程前打开redis-server和redis-cli这两个可执行程序
确认redis启动后就可以开始我们的编程
SpringBoot整合Redis:
第一步:在application中配置redis相应的数据库,主机名,端口号等
spring.data.redis.database=0这个是指我们用的是redis中的0号数据库
第二步:定义我们所需要的实体类(这里实体类一定要实现序列化存储,不然会报错,存不进redis)
第三步:实现我们的Handler(这里我们使用RedisTemplate来简化与Redis的交互)
opsForValue().set方法为往redis中存入数据或者修改数据(第一个参数为键,第二个为值)
opsForValue().get方法为从redis中查询数据
opsForValue().delete方法为从reidis中删除数据
第四步:就可以启动我们的程序,通过postman传入数据进行验证
注:我们传入的一定要是json格式
至此我们简单实现SpingBoot整合Redis就ok了
源码:
application.properties
spring.application.name=Spring_Boot_Redis_Test02 spring.data.redis.database=0 spring.data.redis.host=localhost spring.data.redis.port=6379
实体类Student(这里up用了@Data注解,但是还是使用了getter和setter,是因为up发现在启动时实现查找的时候,找不到对应的getter时常会报错,所以还是加上保险些)
package org.example.spring_boot_redis_test02.Entity; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class Student implements Serializable { private Integer id; private String name; private Date birthday; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
Handler启动类
package org.example.spring_boot_redis_test02.Handler; import org.example.spring_boot_redis_test02.Entity.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.*; @RequestMapping("/redis_zmh") @RestController public class Handler_zmh { @Autowired private RedisTemplate redisTemplate; @RequestMapping("/set") public void set(@RequestParam String key , @RequestBody Student object) { redisTemplate.opsForValue().set(key ,object); } @RequestMapping("/get/{key}") public Student get(@PathVariable("key") String key) { return (Student) redisTemplate.opsForValue().get(key); } @RequestMapping("/delete/{key}") public boolean delete(@PathVariable("key") String key) { return redisTemplate.delete(key); } }