SpringBoot+Mybatis-Plus+MySQL+Redis项目实战

目录

项目结构:

一、导入依赖

二、配置YML文件

三、创建Redis工具类

四、创建配置类(创建自定义Redis模板)

五、实体类及数据库表结构

数据库表结构:

实体类:

六、mapper层

StudentMapper

 七、service层

IStudentService

八、controller层

StudentController

九、启动类

十、测试(使用Postman发请求)

1.新增数据

2.查询数据

3.修改数据

4.删除数据(逻辑删除)


项目结构:

一、导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.13</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.apesource</groupId>
    <artifactId>springboot_redis_02</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_redis_02</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--spring+springMVC-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

二、配置YML文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/maven?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false
    username: root
    password: 123456
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

三、创建Redis工具类

package com.apesource.springboot_redis_02.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author 崔世博
 * @version 1.0
 * @since 2024/9/24
 */

@Component
public class RedisUtil {

    @Autowired(required = false)
    private RedisTemplate jsonRedisTemplate;

    // =========================================================

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                jsonRedisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return jsonRedisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return jsonRedisTemplate.hasKey(key);
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                jsonRedisTemplate.delete(key[0]);
            } else {
                jsonRedisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }


    // ============================String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : jsonRedisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */

    public boolean set(String key, Object value) {
        try {
            jsonRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */

    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                jsonRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return jsonRedisTemplate.opsForValue().increment(key, delta);
    }


    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return jsonRedisTemplate.opsForValue().increment(key, -delta);
    }


    // ================================Map=================================

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     */
    public Object hget(String key, String item) {
        return jsonRedisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
        return jsonRedisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            jsonRedisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            jsonRedisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            jsonRedisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            jsonRedisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        jsonRedisTemplate.opsForHash().delete(key, item);
    }


    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return jsonRedisTemplate.opsForHash().hasKey(key, item);
    }


    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     */
    public double hincr(String key, String item, double by) {
        return jsonRedisTemplate.opsForHash().increment(key, item, by);
    }


    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     */
    public double hdecr(String key, String item, double by) {
        return jsonRedisTemplate.opsForHash().increment(key, item, -by);
    }


    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     */
    public Set<Object> sGet(String key) {
        try {
            return jsonRedisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return jsonRedisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values) {
        try {
            return jsonRedisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = jsonRedisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 获取set缓存的长度
     *
     * @param key 键
     */
    public long sGetSetSize(String key) {
        try {
            return jsonRedisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */

    public long setRemove(String key, Object... values) {
        try {
            Long count = jsonRedisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    // ===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return jsonRedisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 获取list缓存的长度
     *
     * @param key 键
     */
    public long lGetListSize(String key) {
        try {
            return jsonRedisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     */
    public Object lGetIndex(String key, long index) {
        try {
            return jsonRedisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     */
    public boolean lSet(String key, Object value) {
        try {
            jsonRedisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            jsonRedisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            jsonRedisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            jsonRedisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */

    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            jsonRedisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */

    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = jsonRedisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

}

四、创建配置类(创建自定义Redis模板)

package com.apesource.springboot_redis_02.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 崔世博
 * @version 1.0
 * @since 2024/9/24
 */
@Configuration
public class RedisConfig {
    /**
     * 自定义Redis模板
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<Object, Object> jsonRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> Template = new RedisTemplate<Object, Object>();
        Template.setKeySerializer(new StringRedisSerializer());
        Template.setDefaultSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
        Template.setConnectionFactory(redisConnectionFactory);
        return Template;
    }

}

五、实体类及数据库表结构

数据库表结构:

CREATE TABLE `student`  (
  `stu_id` int(11) NOT NULL AUTO_INCREMENT,
  `stu_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `nick_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `stu_age` int(255) NULL DEFAULT NULL,
  `is_delete` int(255) NULL DEFAULT NULL,
  PRIMARY KEY (`stu_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

实体类:

package com.apesource.springboot_redis_02.pojo;

import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author 崔世博
 * @version 1.0
 * @since 2024/9/24
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
@TableName("student")
public class Student {
    @TableId(value = "stu_id", type = IdType.AUTO)
    private int stuId;
    @TableField("stu_name")
    private String stuName;
    @TableField("nick_name")
    private String nickName;
    @TableField("stu_age")
    private int stuAge;

    //用于逻辑删除
    //@TableLogic(value = "默认值",delval = "删除后默认值")
    @TableLogic(value = "0",delval = "1")
    private int isDelete;

}

六、mapper层

StudentMapper

package com.apesource.springboot_redis_02.mapper;

import com.apesource.springboot_redis_02.pojo.Student;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * @author 崔世博
 * @version 1.0
 * @since 2024/9/24
 */
public interface StudentMapper extends BaseMapper<Student> {
}

 七、service层

IStudentService

package com.apesource.springboot_redis_02.service;

import com.apesource.springboot_redis_02.pojo.Student;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * @author 崔世博
 * @version 1.0
 * @since 2024/9/24
 */
public interface IStudentService extends IService<Student> {
    /**
     * 获取用户策略:先从缓存中获取用户,没有则取数据表中数据,再将数据写入缓存
     */
    public Student findById(Integer id);

    /**
     * 删除用户策略:删除数据表中数据,然后删除缓存
     */
    public boolean deleteStudentById(Integer id);

    /**
     * 修改用户:先修改数据库中数据,修改缓存中数据
     */
    public boolean updateStudent(Student student);

    /**
     * 新增用户:先新增数据库,再存到缓存中
     */
    public boolean addStudent(Student student);
}

StudentServiceImpl

package com.apesource.springboot_redis_02.service;

import com.apesource.springboot_redis_02.mapper.StudentMapper;
import com.apesource.springboot_redis_02.pojo.Student;
import com.apesource.springboot_redis_02.util.RedisUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 崔世博
 * @version 1.0
 * @since 2024/9/24
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
    @Autowired(required = false)
    StudentMapper mapper;

    @Autowired
    RedisUtil redisUtil;


    /**
     * 获取用户策略:先从缓存中获取用户,没有则取数据表中数据,再将数据写入缓存
     */
    @Override
    public Student findById(Integer id) {
        String key = "student:id" + id;
        //判断key是否在缓存中存在
        boolean isExist = redisUtil.hasKey(key);
        if (isExist) {
            //如果在缓存中存在,直接获取并返回
            Object object = redisUtil.get(key);
            //类型转换
            ObjectMapper change = new ObjectMapper();
            Student student = change.convertValue(object, Student.class);
            System.out.println("====================从缓存中获取数据====================");
            System.out.println("姓名:" + student.getStuName());
            System.out.println("=====================================================");
            //将student  return
            return student;
        } else {
            //不存在缓存,先从数据库中获取,在保存至redis,最后返回用户
            //如果缓存中不存在则去数据库查找数据
            Student student = mapper.selectById(id);
            System.out.println("====================从数据库中获取数据====================");
            System.out.println("姓名:" + student.getStuName());
            System.out.println("=======================================================");
            if (student != null) {
                //将数据放入缓存
                redisUtil.set(key, student);
            }
            return student;
        }
    }


    /**
     * 删除用户策略:删除数据表中数据,然后删除缓存
     */
    @Override
    public boolean deleteStudentById(Integer id) {
        //删除数据库表中的数据
        int row = mapper.deleteById(id);
        String key = "student:id" + id;
        //如果删除成功,删除缓存中的数据
        if (row > 0) {
            //判断缓存中是否存在数据
            boolean b = redisUtil.hasKey(key);
            if (b) {
                //存在则删除
                redisUtil.del(key);
                return true;
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean updateStudent(Student student) {
        //修改数据库表数据
        int row = mapper.updateById(student);
        String key = "student:id" + student.getStuId();
        if (row > 0) {
            //判断缓存中是否有该学生数据
            if (redisUtil.hasKey(key)) {
                redisUtil.set(key, student);
                return true;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    @Override
    public boolean addStudent(Student student) {
        int row = mapper.insert(student);
        if (row > 0) {
            //mybatis自动主键回填
            String key = "student:id" + student.getStuId();
            //将数据存入redis
            redisUtil.set(key, student);
            return true;
        } else {
            return false;
        }
    }


}

八、controller层

StudentController

package com.apesource.springboot_redis_02.congtroller;

import com.apesource.springboot_redis_02.pojo.Student;
import com.apesource.springboot_redis_02.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 崔世博
 * @version 1.0
 * @since 2024/9/24
 */
@RestController
public class StudentController {

    @Autowired
    IStudentService service;

    
    @RequestMapping("/findbyid/{id}")
    public Student findById(@PathVariable int id) {
        return service.findById(id);
    }

    @RequestMapping("/delbyid/{id}")
    public String delById(@PathVariable int id) {
        if (service.deleteStudentById(id)) {
            //删除成功
            System.out.println("删除成功!");
            return "成功";
        } else {
            System.out.println("删除失败!");
            return "失败";
        }
    }

    @RequestMapping("/update")
    public String update(@RequestBody Student student) {
        if (service.updateStudent(student)) {
            return "修改成功";
        } else {
            return "修改失败";
        }
    }

    @PostMapping("/add")
    public String add(@RequestBody Student student){
        if (service.addStudent(student)){
            return "新增成功";
        }else {
            return "新增失败";
        }
    }

}

九、启动类

package com.apesource.springboot_redis_02;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@MapperScan(basePackages = "com.apesource.springboot_redis_02.mapper")
public class SpringbootRedis02Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootRedis02Application.class, args);
    }

}

十、测试(使用Postman发请求)

1.新增数据

结果:

redis中

MySQL中

2.查询数据

3.修改数据

redis中:

MySQL中:

4.删除数据(逻辑删除)

redis中

MySQL中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值