Spring Boot整合Redis之CURD

1.在IDEA中创建MAVEN工程
2.在pom.xml中引入依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</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>

创建实体类
在这里插入图片描述

package com.mj.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;
}

创建controller
在这里插入图片描述

package com.mj.entity.com.mj.controller;

import com.mj.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")
    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);
        
    }
}

创建配置文件
在这里插入图片描述

spring:
  redis:
    database: 0
    host: localhost
    port: 6379

创建启动类

package com.mj;


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);
    }
}
发布了42 篇原创文章 · 获赞 0 · 访问量 942

猜你喜欢

转载自blog.csdn.net/mojiezhao/article/details/104137474