1、创建Maven工程
pom中引入相关依赖
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.5.6</version>
</parent>
<dependencies>
<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>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2、创建实体类
实体类需要实现序列化接口,否则无法存入Redis数据库
package com.robert.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 Double score;
private Date birthday;
}
3、创建控制器
package com.robert.controller;
import com.robert.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudentHandler {
@Autowired
private RedisTemplate redisTemplate;
@PostMapping("/set")
// 注解RequestBody负责将客户端传入的json数据转换为Java对象
public void set(@RequestBody Student student){
redisTemplate.opsForValue().set("student", student);
}
@GetMapping("/get/{key}")
public Student get(@PathVariable("key") String key){
return (Student)redisTemplate.opsForValue().get(key);
}
@DeleteMapping("/delete/{key}")
public boolean delete(@PathVariable("key") String key){
redisTemplate.delete(key);
return redisTemplate.hasKey(key);
}
}
4、配置文件application.yml
spring:
redis:
database: 0
host: localhost
port: 6379
server:
port: 8090
5、创建启动类
package com.robert;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
其实是Spring Data Redis在操作Redis库
可以使用Postman进行http测试