展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > springboot+mybatisplus+redis的demo怎么实现

springboot+mybatisplus+redis的demo怎么实现

Redis Assistant
Redis Assistant

Redis Assistant 是一款为Redis设计的高效可视化管理与监控工具,提供多种操作模式,高效处理服务器数据。日常使用里的持续防护和信息管理会更突出,适合把安全控制放进长期使用流程中的场景。

¥19
Windows/macOS/Linux 2026-08-22
正版软件 Windows macOS软件 Linux 数据库管理工具
立即下载

1.pom.xml中倒入需要的jar包4.0.0org.examplespringboot_redis_demo1.0-SNAPSHOTorg.springframework.bootspring-boot-starter-parent2.5.0org.springframework.bootspring-boot-starter-web2.5.0mysqlmysql-connector-java8.0.25org.springframework.bootspring-boot-starter-jdbc2

本文目录

    1.pom.xml中倒入需要的jar包

    
    
        4.0.0
    
        org.example
        springboot_redis_demo
        1.0-SNAPSHOT
    
        
            org.springframework.boot
            spring-boot-starter-parent
            2.5.0
        
    
        
    
            
            
                org.springframework.boot
                spring-boot-starter-web
                2.5.0
            
    
            
            
                mysql
                mysql-connector-java
                8.0.25
            
    
            
            
                org.springframework.boot
                spring-boot-starter-jdbc
                2.5.0
            
    
            
            
                com.alibaba
                druid
                1.2.6
            
    
            
            
                com.baomidou
                mybatis-plus-boot-starter
                3.4.3
            
    
            
            
                com.baomidou
                mybatis-plus-generator
                3.4.1
            
    
            
            
                org.springframework.boot
                spring-boot-starter-freemarker
                2.5.0
            
    
            
            
                org.springframework.boot
                spring-boot-starter-data-redis
                2.5.0
            
    
            
            
                org.projectlombok
                lombok
                1.18.20
                provided
            
    
            
            
                org.springframework.boot
                spring-boot-starter-test
                2.5.0
                test
            
    
            
            
                junit
                junit
                4.13.2
                test
            
    
            
            
                io.springfox
                springfox-swagger2
                3.0.0
            
    
            
            
                io.springfox
                springfox-swagger-ui
                3.0.0
            
    
        
    
    

    2.application.yml配置信息

    #端口
    server:
      port: 1010
    
    #配置数据源
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8&useSSL=false
        username: root
        password: 123456
        type: com.alibaba.druid.pool.DruidDataSource
    
      #配置redis
      redis:
        host: 127.0.0.1
        port: 6379
        database: 0
        password: 123456

    3.启动类需要的注解

    package com.zengjx.project;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    
    /**
     * @author fastrabbit
     * @date 2021/6/9 9:43
     */
    @SpringBootApplication
    @EnableCaching
    @MapperScan("com.zengjx.project.*.mapper")
    public class RedisApp {
    
        public static void main(String[] args) {
            SpringApplication.run(RedisApp.class, args);
        }
    
    }

    4.mybatisplus模板——baseQuery

    package ${cfg.packagePath}.common;
    
    import com.baomidou.mybatisplus.annotation.TableField;
    import lombok.Data;
    
    /**
     * @author ${author}
     * @date ${date}
     */
    @Data
    public class BaseQuery {
    
    	/**
         * 当前页数  默认为1
         */
        @TableField(exist=false)
        private Integer page = 1;
    
        /**
         * 每页数据量  默认为10
         */
        @TableField(exist=false)
        private Integer rows =10;
    
    }

    5.mybatisplus模板——controller

    package ${package.Controller};
    
    import ${cfg.packagePath}.common.Result;
    import ${package.Entity}.${entity};
    import ${package.Service}.${table.serviceName};
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    <#if restControllerStyle>
    import org.springframework.web.bind.annotation.RestController;
    <#else>
    import org.springframework.stereotype.Controller;
    
    
    import java.util.List;
    <#if superControllerClassPackage??>
    import ${superControllerClassPackage};
    
    
    /**
     * @author ${author}
     * @date ${date}
     */
    @Api(tags = {"${table.comment!}"})
    <#if restControllerStyle>
    @RestController
    <#else>
    @Controller
    
    @RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}")
    <#if kotlin>
    class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()
    <#else>
    <#if superControllerClass??>
    public class ${table.controllerName} extends ${superControllerClass} {
    <#else>
    public class ${table.controllerName} {
    
    
        private Logger logger = LoggerFactory.getLogger(getClass());
    
        @Autowired
        private ${table.serviceName} ${(table.serviceName?substring(1))?uncap_first};
    
        /**
         * @author fastrabbit
         * @description 根据id查询单个数据
         * @date ${date}
         */
        @ApiOperation(value = "根据id查询单个数据")
        @RequestMapping(value = "/getById")
        public Result<${entity}> getById(@RequestBody ${entity} ${entity?uncap_first}){
    
            return ${(table.serviceName?substring(1))?uncap_first}.getById(${entity?uncap_first});
    
        }
    
        /**
         * @author fastrabbit
         * @description 根据查询条件查询分页数据
         * @date ${date}
         */
        @ApiOperation(value = "根据查询条件查询分页数据")
        @RequestMapping(value = "/list")
        public Result> findListByPage(@RequestBody ${entity} ${entity?uncap_first}){
    
            return ${(table.serviceName?substring(1))?uncap_first}.findListByPage(${entity?uncap_first});
    
        }
    
        /**
         * @author fastrabbit
         * @description 查询所有数据
         * @date ${date}
         */
        @ApiOperation(value = "查询所有数据")
        @RequestMapping(value = "/getAll")
        public Result> getAll(){
    
            return ${(table.serviceName?substring(1))?uncap_first}.getAll();
    
        }
    
        /**
         * @author fastrabbit
         * @description 新增单个数据
         * @date ${date}
         */
        @ApiOperation(value = "新增单个数据")
        @RequestMapping(value = "/insert", method = RequestMethod.POST)
        public Result insert(@RequestBody ${entity} ${entity?uncap_first}){
    
            return ${(table.serviceName?substring(1))?uncap_first}.insert(${entity?uncap_first});
    
        }
    
        /**
         * @author fastrabbit
         * @description 删除单个数据
         * @date ${date}
         */
        @ApiOperation(value = "删除单个数据")
        @RequestMapping(value = "/delete")
        public Result delete(@RequestBody ${entity} ${entity?uncap_first}){
    
            return ${(table.serviceName?substring(1))?uncap_first}.delete(${entity?uncap_first});
    
        }
    
        /**
         * @author fastrabbit
         * @description 修改单个数据
         * @date ${date}
         */
        @ApiOperation(value = "修改单个数据")
        @RequestMapping(value = "/update", method = RequestMethod.POST)
        public Result update(@RequestBody ${entity} ${entity?uncap_first}){
    
            return ${(table.serviceName?substring(1))?uncap_first}.update(${entity?uncap_first});
    
        }
    
     }
    

    6.mybatisplus模板——entity

    package ${package.Entity};
    
    <#list table.importPackages as pkg>
    import ${pkg};
    
    <#if swagger2>
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    
    import ${cfg.packagePath}.common.BaseQuery;
    <#if entityLombokModel>
    import lombok.Data;
    import lombok.EqualsAndHashCode;
        <#if chainModel>
    import lombok.experimental.Accessors;
        
    
    
    /**
     * @author ${author}
     * @date ${date}
     */
    <#if entityLombokModel>
    @Data
        <#if superEntityClass??>
    @EqualsAndHashCode(callSuper = true)
        <#else>
    @EqualsAndHashCode(callSuper = false)
        
        <#if chainModel>
    @Accessors(chain = true)
        
    
    <#if table.convert>
    @TableName("${table.name}")
    
    <#if swagger2>
    @ApiModel(value="${entity}对象", description="${table.comment!}")
    
    <#if superEntityClass??>
    public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> {
    <#elseif activeRecord>
    public class ${entity} extends Model<${entity}> {
    <#else>
    public class ${entity} extends BaseQuery implements Serializable {
    
    
    <#if entitySerialVersionUID>
        private static final long serialVersionUID = 1L;
    
    <#-- ----------  BEGIN 字段循环遍历  ---------->
    <#list table.fields as field>
        <#if field.keyFlag>
            <#assign keyPropertyName="${field.propertyName}"/>
        
    
        <#if field.comment!?length gt 0>
            <#if swagger2>
        @ApiModelProperty(value = "${field.comment}")
            <#else>
        /**
         * ${field.comment}
         */
            
        
        <#if field.keyFlag>
            <#-- 主键 -->
            <#if field.keyIdentityFlag>
        @TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
            <#elseif idType??>
        @TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
            <#elseif field.convert>
        @TableId("${field.annotationColumnName}")
            
            <#-- 普通字段 -->
        <#elseif field.fill??>
        <#-- -----   存在字段填充设置   ----->
            <#if field.convert>
        @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
            <#else>
        @TableField(fill = FieldFill.${field.fill})
            
        <#elseif field.convert>
        @TableField("${field.annotationColumnName}")
        
        <#-- 乐观锁注解 -->
        <#if (versionFieldName!"") == field.name>
        @Version
        
        <#-- 逻辑删除注解 -->
        <#if (logicDeleteFieldName!"") == field.name>
        @TableLogic
        
        private ${field.propertyType} ${field.propertyName};
    
    <#------------  END 字段循环遍历  ---------->
    
    <#if !entityLombokModel>
        <#list table.fields as field>
            <#if field.propertyType == "boolean">
                <#assign getprefix="is"/>
            <#else>
                <#assign getprefix="get"/>
            
        public ${field.propertyType} ${getprefix}${field.capitalName}() {
            return ${field.propertyName};
        }
    
        <#if chainModel>
        public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        <#else>
        public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
        
            this.${field.propertyName} = ${field.propertyName};
            <#if chainModel>
            return this;
            
        }
        
    
    
    <#if entityColumnConstant>
        <#list table.fields as field>
        public static final String ${field.name?upper_case} = "${field.name}";
    
        
    
    <#if activeRecord>
        @Override
        protected Serializable pkVal() {
        <#if keyPropertyName??>
            return this.${keyPropertyName};
        <#else>
            return null;
        
        }
    
    
    <#if !entityLombokModel>
        @Override
        public String toString() {
            return "${entity}{" +
        <#list table.fields as field>
            <#if field_index==0>
                "${field.propertyName}=" + ${field.propertyName} +
            <#else>
                ", ${field.propertyName}=" + ${field.propertyName} +
            
        
            "}";
        }
    
    }

    7.mybatisplus模板——mapper

    package ${package.Mapper};
    
    import ${package.Entity}.${entity};
    import ${superMapperClassPackage};
    
    /**
     * @author ${author}
     * @date ${date}
     */
    <#if kotlin>
    interface ${table.mapperName} : ${superMapperClass}<${entity}>
    <#else>
    public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
    
    }
    

    8.mybatisplus模板——mybatisplusConfig

    package ${cfg.packagePath}.globalconfig;
    
    import com.baomidou.mybatisplus.annotation.DbType;
    import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
    import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    /**
     * @author ${author}
     * @date ${date}
     */
    @Configuration
    @EnableTransactionManagement
    public class MybatisPlusConfig {
    
        /**
         * @author fastrabbit
         * @description 获取分页插件
         * @date ${date}
         */
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
            return interceptor;
        }
    
    }

    9.mybatisplus模板——result

    package ${cfg.packagePath}.common;
    
    import lombok.Data;
    
    /**
     * @author ${author}
     * @date ${date}
     */
    @Data
    public class Result {
    
        /**
         * 是否成功  默认为成功
         */
        private Boolean success = true;
    
        /**
         * 状态码  默认为200
         */
        private Integer code = 200;
    
        /**
         * 返回信息描述
         */
        private String message;
    
        /**
         * 返回数据
         */
        private T data;
    
        /**
         * 返回数据量
         */
        private Integer total;
    
    }

    10.mybatisplus模板——service

    package ${package.Service};
    
    import ${superServiceClassPackage};
    import ${cfg.packagePath}.common.Result;
    import ${package.Entity}.${entity};
    
    import java.util.List;
    
    /**
     * @author ${author}
     * @date ${date}
     */
    <#if kotlin>
    interface ${table.serviceName} : ${superServiceClass}<${entity}>
    <#else>
    public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
    
        /**
         * @author fastrabbit
         * @description 根据id查询单个数据
         * @date ${date}
         */
        Result<${entity}> getById(${entity} ${entity?uncap_first});
    
        /**
         * @author fastrabbit
         * @description 根据查询条件查询分页数据
         * @date ${date}
         */
        Result> findListByPage(${entity} ${entity?uncap_first});
    
        /**
         * @author fastrabbit
         * @description 查询所有数据
         * @date ${date}
         */
        Result> getAll();
    
        /**
         * @author fastrabbit
         * @description 新增单个数据
         * @date ${date}
         */
        Result insert(${entity} ${entity?uncap_first});
    
        /**
        * @author fastrabbit
        * @description 修改单个数据
        * @date ${date}
        */
        Result update(${entity} ${entity?uncap_first});
    
        /**
         * @author fastrabbit
         * @description 删除单个数据
         * @date ${date}
         */
        Result delete(${entity} ${entity?uncap_first});
    
    }
    

    11.mybatisplus模板——serviceImpl

    package ${package.ServiceImpl};
    
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import ${cfg.packagePath}.common.Result;
    import ${package.Entity}.${entity};
    import ${package.Mapper}.${table.mapperName};
    import ${package.Service}.${table.serviceName};
    import ${superServiceImplClassPackage};
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.List;
    
    /**
     * @author ${author}
     * @date ${date}
     */
    @Service
    @Transactional(rollbackFor=Exception.class)
    <#if kotlin>
    open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
    
    }
    <#else>
    public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
    
        @Autowired
        private ${table.mapperName} ${table.mapperName?uncap_first};
    
        /**
         * @author fastrabbit
         * @description 根据id查询单个数据
         * @date ${date}
         */
        @Override
        public Result<${entity}> getById(Food food) {
    
            Result<${entity}> foodResult = new Result<>();
            foodResult.setData(foodMapper.selectById(food.getId()));
            return foodResult;
    
        }
    
        /**
         * @author fastrabbit
         * @description 根据查询条件查询分页数据
         * @date ${date}
         */
        @Override
        public Result> findListByPage(Food food) {
    
            Result> listResult = new Result<>();
            Page<${entity}> foodPage = new Page<>(food.getPage(), food.getRows());
            QueryWrapper<${entity}> foodQueryWrapper = new QueryWrapper<>();
            List<${entity}> records = foodMapper.selectPage(foodPage, foodQueryWrapper).getRecords();
            listResult.setData(records);
            listResult.setTotal(records.size());
            return listResult;
    
        }
    
        /**
         * @author fastrabbit
         * @description 查询所有数据
         * @date ${date}
         */
        @Override
        public Result> getAll() {
    
            Result> foodResult = new Result<>();
            List<${entity}> foods = foodMapper.selectList(null);
            foodResult.setData(foods);
            foodResult.setTotal(foods.size());
            return foodResult;
    
        }
    
        /**
         * @author fastrabbit
         * @description 新增单个数据
         * @date ${date}
         */
        @Override
        public Result insert(Food food) {
    
            Result objectResult = new Result<>();
            foodMapper.insert(food);
            return objectResult;
    
        }
    
        /**
         * @author fastrabbit
         * @description 修改单个数据
         * @date ${date}
         */
        @Override
        public Result update(Food food) {
    
            Result objectResult = new Result<>();
            foodMapper.updateById(food);
            return objectResult;
    
        }
    
        /**
         * @author fastrabbit
         * @description 删除单个数据
         * @date ${date}
         */
        @Override
        public Result delete(Food food) {
    
            Result objectResult = new Result<>();
            foodMapper.deleteById(food.getId());
            return objectResult;
    
        }
    
    }
    

    12.mybatisplus模板代码生成器——CodeGenerator

    package com.zengjx.project;
    
    import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
    import com.baomidou.mybatisplus.core.toolkit.StringPool;
    import com.baomidou.mybatisplus.core.toolkit.StringUtils;
    import com.baomidou.mybatisplus.generator.AutoGenerator;
    import com.baomidou.mybatisplus.generator.InjectionConfig;
    import com.baomidou.mybatisplus.generator.config.*;
    import com.baomidou.mybatisplus.generator.config.po.TableInfo;
    import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
    
    import java.io.File;
    import java.util.*;
    
    /**
     * @author fastrabbit
     * @date 2021/5/25 9:28
     */
    public class CodeGenerator {
    
        /**
         * 

         * 读取控制台内容      * 

         */     public static String scanner(String tip) {         Scanner scanner = new Scanner(System.in);         StringBuilder help = new StringBuilder();         help.append("请输入" + tip + ":");         System.out.println(help.toString());         if (scanner.hasNext()) {             String ipt = scanner.next();             if (StringUtils.isNotBlank(ipt)) {                 return ipt;             }         }         throw new MybatisPlusException("请输入正确的" + tip + "!");     }     public static void main(String[] args) {         // 代码生成器         AutoGenerator mpg = new AutoGenerator();         // 全局配置         GlobalConfig gc = new GlobalConfig();         // 获取到当前项目的根目录         String projectPath = System.getProperty("user.dir");         // 在指定的文件夹下生成文件的输出目录         gc.setOutputDir(projectPath + "/src/main/java");         // 设置类注释中的类的作者         gc.setAuthor("fastrabbit");         // 是否打开输出目录         gc.setOpen(false);         // 实体属性 Swagger2 注解         gc.setSwagger2(true);         // 开启activeRecord模式 开启后entity会继承Model类         gc.setActiveRecord(false);         // XML ResultMap: mapper.xml生成查询映射结果         gc.setBaseResultMap(true);         // 是否覆盖原来的文件         gc.setFileOverride(false);         mpg.setGlobalConfig(gc); //======================================================================================================================         // 数据源配置         DataSourceConfig dsc = new DataSourceConfig();         dsc.setUrl("jdbc:mysql://192.168.0.199:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");         // dsc.setSchemaName("public");         dsc.setDriverName("com.mysql.cj.jdbc.Driver");         dsc.setUsername("root");         dsc.setPassword("123456");         mpg.setDataSource(dsc); //======================================================================================================================         // 包配置         PackageConfig pc = new PackageConfig();         pc.setModuleName(scanner("模块名"));         // 设置包的路径  该路径为 com.公司名.项目名         String packagePath = "com.zengjx.project";         pc.setParent(packagePath);         mpg.setPackageInfo(pc); //======================================================================================================================         // 自定义配置         InjectionConfig cfg = new InjectionConfig() {             @Override             public void initMap() {                 Map map = new HashMap<>();                 List tableInfoList = this.getConfig().getTableInfoList();                 for (TableInfo tableInfo : tableInfoList) {                     //项目包的路径 使用到的类有BaseQuery、MybatisPlusConfig、Result                     map.put("packagePath", packagePath);                 }                 this.setMap(map);             }         }; //======================================================================================================================         // 如果模板引擎是 freemarker         String templatePath = "/templates/mapper.xml.ftl";         // 如果模板引擎是 velocity         // String templatePath = "/templates/mapper.xml.vm";         // 自定义输出配置         List focList = new ArrayList<>();         // 自定义配置会被优先输出  这是一个示例         focList.add(new FileOutConfig(templatePath) {             @Override             public String outputFile(TableInfo tableInfo) {                 // 自定义输出文件名,如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!                 // 指定xml文件输出位置                 return projectPath + "/src/main/resources/com/zengjx/project/" + pc.getModuleName() + "/mapper"                         + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;             }         });         // 自定义controller的代码模板         templatePath = "/templates/controller.java.ftl";         // 自定义配置会被优先输出         focList.add(new FileOutConfig(templatePath) {             @Override             public String outputFile(TableInfo tableInfo) {                 // 自定义输出文件名 + pc.getModuleName()                 String expand = projectPath + "/src/main/java/com/zengjx/project/" + pc.getModuleName() + "/" + "controller";                 return String.format((expand + File.separator + "%s" + ".java") , tableInfo.getControllerName());             }         });         // 自定义entity的代码模板         templatePath = "/templates/entity.java.ftl";         // 自定义配置会被优先输出         focList.add(new FileOutConfig(templatePath) {             @Override             public String outputFile(TableInfo tableInfo) {                 // 自定义输出文件名 + pc.getModuleName()                 String expand = projectPath + "/src/main/java/com/zengjx/project/" + pc.getModuleName() + "/" + "entity";                 return String.format((expand + File.separator + "%s" + ".java") , tableInfo.getEntityName());             }         });         // 自定义service的代码模板         templatePath = "/templates/service.java.ftl";         // 自定义配置会被优先输出         focList.add(new FileOutConfig(templatePath) {             @Override             public String outputFile(TableInfo tableInfo) {                 // 自定义输出文件名 + pc.getModuleName()                 String expand = projectPath + "/src/main/java/com/zengjx/project/" + pc.getModuleName() + "/" + "service";                 return String.format((expand + File.separator + "%s" + ".java") , tableInfo.getServiceName());             }         });         // 自定义BaseQuery代码模板         templatePath = "/templates/baseQuery.java.ftl";         // 自定义配置会被优先输出         focList.add(new FileOutConfig(templatePath) {             @Override             public String outputFile(TableInfo tableInfo) {                 // 自定义输出文件名 + pc.getModuleName()                 String expand = projectPath + "/src/main/java/com/zengjx/project/" + "common";                 return String.format((expand + File.separator + "%s" + ".java") , "BaseQuery");             }         });         // 自定义Result代码模板         templatePath = "/templates/result.java.ftl";         // 自定义配置会被优先输出         focList.add(new FileOutConfig(templatePath) {             @Override             public String outputFile(TableInfo tableInfo) {                 // 自定义输出文件名 + pc.getModuleName()                 String expand = projectPath + "/src/main/java/com/zengjx/project/" + "common";                 return String.format((expand + File.separator + "%s" + ".java") , "Result");             }         });         // 自定义全局MybatisPlusConfig代码模板         templatePath = "/templates/mybatisPlusConfig.java.ftl";         // 自定义配置会被优先输出         focList.add(new FileOutConfig(templatePath) {             @Override             public String outputFile(TableInfo tableInfo) {                 // 自定义输出文件名 + pc.getModuleName()                 String expand = projectPath + "/src/main/java/com/zengjx/project/" + "globalconfig";                 return String.format((expand + File.separator + "%s" + ".java") , "MybatisPlusConfig");             }         }); //======================================================================================================================         cfg.setFileOutConfigList(focList);         mpg.setCfg(cfg);         // 配置模板         TemplateConfig templateConfig = new TemplateConfig();         // 配置自定义输出模板         // 指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别         // templateConfig.setEntity("templates/entity2.java");         // templateConfig.setService();         // templateConfig.setController();         templateConfig.setXml(null);         mpg.setTemplate(templateConfig); //======================================================================================================================         // 策略配置         StrategyConfig strategy = new StrategyConfig();         // 数据库表映射到实体的命名策略  下划线转驼峰命名         strategy.setNaming(NamingStrategy.underline_to_camel);         // 数据库表字段映射到实体的命名策略  下划线转驼峰命名         strategy.setColumnNaming(NamingStrategy.underline_to_camel);         // 设置entity继承的父类         //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");         // 设置实体类是否为lombok模型         strategy.setEntityLombokModel(true);         // 设置controller为restful风格         strategy.setRestControllerStyle(true);         // 设置controller的公共父类         //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");         // 设置entity公共父类中的公共字段  如果这里设置了那么生成的entity就不会去生成Id了         //strategy.setSuperEntityColumns("id");         // 给那些表创建文件         strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));         // 驼峰转连字符         strategy.setControllerMappingHyphenStyle(true);         // 设置表的前缀         strategy.setTablePrefix(pc.getModuleName() + "_");         // 将表的配置交给代码生成器         mpg.setStrategy(strategy);         // 创建模板引擎         mpg.setTemplateEngine(new FreemarkerTemplateEngine());         // 执行         mpg.execute();     } }

    13.redis的配置文件

    package com.zengjx.project.globalconfig;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.JsonTypeInfo;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.cache.RedisCacheConfiguration;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.cache.RedisCacheWriter;
    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.RedisSerializationContext;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    /**
     * @author fastrabbit
     * @date 2021/6/9 9:55
     */
    @Configuration
    public class RedisConfig extends CachingConfigurerSupport {
    
        /**
         * @description: 将模板RedisTemplate中的key和value进行序列化
         * @param: RedisConnectionFactory
         * @return: RedisTemplate
         * @author: fastrabbit
         * @date: 2021/6/11 9:12
         */
        @Bean
        public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    
            Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
            serializer.setObjectMapper(objectMapper);
    
            RedisTemplate redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setValueSerializer(serializer);
            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
            redisTemplate.setHashValueSerializer(serializer);
            redisTemplate.afterPropertiesSet();
    
            return redisTemplate;
    
        }
    
        /**
         * @description: 设置RedisCacheManager
         * @param: RedisTemplate
         * @return: RedisCacheManager
         * @author: fastrabbit
         * @date: 2021/6/11 9:12
         */
        @Bean
        public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
    
            RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
            RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));
            return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    
        }
    
    }

    14.redis的模板一些常用方法

    package com.zengjx.project.redis.test;
    
    import io.swagger.models.auth.In;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.data.redis.connection.DataType;
    import org.springframework.data.redis.core.*;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.util.*;
    import java.util.concurrent.TimeUnit;
    
    /**
     * @author fastrabbit
     * @date 2021/6/9 9:30
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class RedisTemplateTest {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Test
        public void stringRedisTemplateTest() {
    
            //保存:保存key和value
            redisTemplate.opsForValue().set("stringKey1", "stringKey1_value");
    
            //保存:保存key和value  如果Key存在则返回false  否则保存成功并返回true
            Boolean message1 = redisTemplate.opsForValue().setIfAbsent("stringKey1", "message1");
            System.out.println(message1);
    
            //保存:保存key和value并设置过期时间
            redisTemplate.opsForValue().set("stringKey2", "stringKey2_value", 20, TimeUnit.SECONDS);
    
            //保存:通过map的方式保存key和value
            HashMap hashMap1 = new HashMap<>();
            hashMap1.put("stringKeyHash1", "stringKeyHash1_value");
            hashMap1.put("stringKeyHash2", "stringKeyHash2_value");
            hashMap1.put("stringKeyHash3", "stringKeyHash3_value");
            redisTemplate.opsForValue().multiSet(hashMap1);
    
            //保存:通过map的方式保存key和valu  如果map集合中的所有key在redis中不存在则添加否则不做修改
            HashMap hashMap2 = new HashMap<>();
            hashMap2.put("stringKeyHash3", "stringKeyHash3_value");
            hashMap2.put("stringKeyHash4", "stringKeyHash4_value");
            hashMap2.put("stringKeyHash5", "stringKeyHash5_value");
            redisTemplate.opsForValue().multiSetIfAbsent(hashMap2);
    
            //修改:在原来key值对应的value新增字符串到末尾处
            redisTemplate.opsForValue().set("stringKey3", "stringKey3_value");
            redisTemplate.opsForValue().append("stringKey3", "+新增字符串");
    
            //修改:修改key对应的value值  使用覆盖的方式
            redisTemplate.opsForValue().set("stringKey4", "stringKey4_value");
            redisTemplate.opsForValue().set("stringKey4", "stringKey4_newValue");
    
            //修改:修改key的值
            redisTemplate.opsForValue().set("stringKey5", "stringKey5_value");
            redisTemplate.rename("stringKey5", "newStringKey5");
    
            //修改:修改key的值  如果存在则修改返回ture  否则报错:ERR no such key
            redisTemplate.opsForValue().set("stringKey6", "stringKey6_value");
            Boolean message2 = redisTemplate.renameIfAbsent("stringKey6", "newStringKey6");
            System.out.println(message2);
    
            //修改:修改key的value值并返回原来的value值
            redisTemplate.opsForValue().set("stringKey7", "stringKey7_value");
            String exchange = (String)redisTemplate.opsForValue().getAndSet("stringKey7", "newStringKey7_value");
            System.out.println(exchange);
    
            //查询:获取指定key对应的value值
            redisTemplate.opsForValue().set("stringKey8", "stringKey8_value");
            String stringKey8 = (String)redisTemplate.opsForValue().get("stringKey8");
            System.out.println(stringKey8);
    
            //查询:批量获取到key对应的value值  参数为Collection keys
            ArrayList arrayListKeys = new ArrayList<>();
            arrayListKeys.add("stringKey1");
            arrayListKeys.add("stringKey2");
            arrayListKeys.add("stringKey3");
            List arrayListValues = redisTemplate.opsForValue().multiGet(arrayListKeys);
            for (Object arrayListValue : arrayListValues) {
                System.out.println(arrayListValue);
            }
    
            //查询:获取指定Key的value值并设定截取长度
            redisTemplate.opsForValue().set("stringKey9", "stringKey9_value");
            String stringKey9Value = redisTemplate.opsForValue().get("stringKey9", 1, 5);
            System.out.println(stringKey9Value);
    
            //查询:获取指定key的过期时间
            redisTemplate.opsForValue().set("stringKey10", "stringKey10_value", 666, TimeUnit.SECONDS);
            Long stringKey10Expire = redisTemplate.getExpire("stringKey10", TimeUnit.SECONDS);
            System.out.println(stringKey10Expire);
    
            //查询:从redis中随机获取到一个key值
            String randomKey = redisTemplate.randomKey();
            System.out.println(randomKey);
    
            //查询:返回key的value的类型
            redisTemplate.opsForValue().set("stringKey11", "stringKey11_value");
            DataType stringKey11DataType = redisTemplate.type("stringKey11");
            System.out.println(stringKey11DataType);
    
            //查询:查询匹配的key值  *:匹配任意多个字符  ?:配置单个字符  []:配置括号内的某1个字符
            Set allKeys = redisTemplate.keys("*");
            Set somekeys = redisTemplate.keys("stringKey?");
            Set otherKeys = redisTemplate.keys("stringKey[123]");
    
            //删除:删除单个的key和它的vlue
            redisTemplate.opsForValue().set("stringKey12", "stringKey12_value");
            Boolean deleteStringKey12 = redisTemplate.delete("stringKey12");
            System.out.println(deleteStringKey12);
    
            //删除:批量删除集合中的key值  返回删除了的数量
            redisTemplate.opsForValue().set("stringKey13", "stringKey13_value");
            redisTemplate.opsForValue().set("stringKey14", "stringKey14_value");
            redisTemplate.opsForValue().set("stringKey15", "stringKey15_value");
            ArrayList arrayListDelete = new ArrayList<>();
            arrayListDelete.add("stringKey13");
            arrayListDelete.add("stringKey14");
            arrayListDelete.add("stringKey15");
            Long deleteArrayList = redisTemplate.delete(arrayListDelete);
            System.out.println(deleteArrayList);
    
            //其他:将key序列化为byte[]类型
            redisTemplate.opsForValue().set("stringKey16", "stringKey16_value");
            byte[] stringKey16ByteArray = redisTemplate.dump("stringKey16");
            System.out.println(stringKey16ByteArray);
    
            //其他:将key进行持久化保存
            redisTemplate.opsForValue().set("stringKey17", "stringKey17_value");
            Boolean stringKey17Persist = redisTemplate.persist("stringKey17");
            System.out.println(stringKey17Persist);
    
            //其他:将当前库中的key移动到指定的库中
            redisTemplate.opsForValue().set("stringKey18", "stringKey18_value");
            Boolean stringKey18Move = redisTemplate.move("stringKey18", 1);
            System.out.println(stringKey18Move);
    
            //其他:获取到key的value字符串长度
            redisTemplate.opsForValue().set("stringKey19", "stringKey19_value");
            Long stringKey19Size = redisTemplate.opsForValue().size("stringKey19");
            System.out.println(stringKey19Size);
    
            //其他:查看是否存在指定的key
            Boolean hasStringKey19 = redisTemplate.hasKey("stringKey19");
            System.out.println(hasStringKey19);
    
        }
    
        @Test
        public void hashRedisTemplateTest() {
    
            //保存:保存一个hashMap
            redisTemplate.opsForHash().put("hashKey1", "field1", "field1_value");
    
            //保存:保存一个hashMap  仅当field不存在的时候才保存成功
            Boolean putIfAbsentField = redisTemplate.opsForHash().putIfAbsent("hashKey1", "field1", "field1_value_attach");
            System.out.println(putIfAbsentField);
    
            //保存:通过map的形式添加键值对
            HashMap hashMap3 = new HashMap<>();
            hashMap3.put("field2", "field2_value");
            hashMap3.put("field2_attach1", "field2_attach1_value");
            hashMap3.put("field2_attach2", "field2_attach2_value");
            redisTemplate.opsForHash().putAll("hashKey2", hashMap3);
    
            //修改:
            redisTemplate.opsForHash().put("hashKey3", "field3", "field3_value");
            redisTemplate.opsForHash().put("hashKey3", "field3", "newField3_value");
    
            //查询:获取指定hashKey、field的value值
            redisTemplate.opsForHash().put("hashKey4", "field4", "field4_value");
            String getSpecifyValue = (String)redisTemplate.opsForHash().get("hashKey4", "field4");
            System.out.println(getSpecifyValue);
    
            //查询:获取指定hashKey的map值
            redisTemplate.opsForHash().put("hashKey5", "field5", "field5_value");
            Map getSpecifyMap = redisTemplate.opsForHash().entries("hashKey5");
            for (Object o : getSpecifyMap.keySet()) {
                System.out.println(o);
                System.out.println(getSpecifyMap.get(o));
            }
    
            //查询:获取指定hashkey中的所有field字段
            HashMap hashMap4 = new HashMap<>();
            hashMap4.put("field6", "field6_value");
            hashMap4.put("field6_attach1", "field6_attach1_value");
            hashMap4.put("field6_attach2", "field6_attach2_value");
            redisTemplate.opsForHash().putAll("hashKey6", hashMap4);
            Set getSpecifySet = redisTemplate.opsForHash().keys("hashKey6");
            for (Object o : getSpecifySet) {
                System.out.println(o);
            }
    
            //查询:获取到指定hashKey的field的数量
            HashMap hashMap5 = new HashMap<>();
            hashMap5.put("field7", "fiele7_value");
            hashMap5.put("field7_attach1", "fiele7_attach1_value");
            hashMap5.put("field7_attach2", "fiele7_attach2_value");
            redisTemplate.opsForHash().putAll("hashKey7", hashMap5);
            Long hashKey7Size = redisTemplate.opsForHash().size("hashKey7");
            System.out.println(hashKey7Size);
    
            //查询:获取指定hashKey的所有field的value值
            HashMap hashMap6 = new HashMap<>();
            hashMap6.put("field8", "field8_value");
            hashMap6.put("field8_attach1", "field8_attach1_value");
            hashMap6.put("field8_attach2", "field8_attach2_value");
            redisTemplate.opsForHash().putAll("hashKey8", hashMap6);
            List hashKey8Values = redisTemplate.opsForHash().values("hashKey8");
            for (Object hashKey8Value : hashKey8Values) {
                System.out.println(hashKey8Value);
            }
    
        }
    
        @Test
        public void listRedisTemplateTest() {
    
            //保存:存储在key链表的右边  并返回长度
            Long listKey1Length = redisTemplate.opsForList().rightPush("listKey1", "listKey1_value");
            System.out.println(listKey1Length);
    
            //保存:存储多个值在list的右边  参数为Collect  参数泛型需要和设置的模板的泛型一致,不然保存的是数组而不是数组元素
            redisTemplate.opsForList().rightPush("listKey2", "listKey2_value");
            ArrayList arrayList1 = new ArrayList<>();
            arrayList1.add("listKey2_attach1_value");
            arrayList1.add("listKey2_attach2_value");
            arrayList1.add("listKey2_attach3_value");
            Long listKey2Length1 = redisTemplate.opsForList().rightPushAll("listKey2", "listKey2_attach1_value", "listKey2_attach2_value", "listKey2_attach3_value");
            Long listKey2Length2 = redisTemplate.opsForList().rightPushAll("listKey2", arrayList1);
            System.out.println(listKey2Length1);
            System.out.println(listKey2Length2);
    
            //保存:存储在key连表的左边  并返回长度
            Long listKey3Length1 = redisTemplate.opsForList().leftPush("listKey3", "listKey3_value");
            Long listKey3Length2 = redisTemplate.opsForList().leftPush("listKey3", "listKey3_attach1_value");
            System.out.println(listKey3Length1);
            System.out.println(listKey3Length2);
    
            //保存:存储多个值在list的左边  参数为collect
            redisTemplate.opsForList().leftPush("listKey4", "listKey4_value");
            ArrayList arrayList2 = new ArrayList<>();
            arrayList2.add("listKey4_attach1_value");
            arrayList2.add("listKey4_attach2_value");
            arrayList2.add("listKey4_attach3_value");
            Long listKey4Length1 = redisTemplate.opsForList().leftPushAll("listKey4", "listKey4_attach1_value", "listKey4_attach2_value", "listKey4_attach3_value");
            Long listKey4Length2 = redisTemplate.opsForList().leftPushAll("listKey4", arrayList2);
            System.out.println(listKey4Length1);
            System.out.println(listKey4Length2);
    
            //保存:在指定的key中的pivot(key的value)的前面添加值  如果存在则添加  否则不添加并返回-1
            redisTemplate.opsForList().leftPush("listKey5", "listKey5_value");
            Long listKey5Length1 = redisTemplate.opsForList().leftPush("listKey5", "nothing", "listKey5_attach1_value");
            System.out.println(listKey5Length1);
    
            //保存:在指定的key中的pivot(key的value)的后面添加值  如果存在则添加  否则不添加并返回-1
            redisTemplate.opsForList().rightPush("listKey6", "listKey6_value");
            Long listKey6Length1 = redisTemplate.opsForList().rightPush("listKey6", "nothing", "listKey6_attach1_value");
            System.out.println(listKey6Length1);
    
            //保存:只有当链表存在的时候才加入  否则返回0
            Long nothing1 = redisTemplate.opsForList().leftPushIfPresent("nothing", "test");
            Long nothing2 = redisTemplate.opsForList().rightPushIfPresent("nothing", "test");
            System.out.println(nothing1);
            System.out.println(nothing2);
    
            //修改:修改指定索引处的值  如果索引大于链表长度或报错ERR index out of range
            redisTemplate.opsForList().rightPush("listKey7", "listKey7_value");
            redisTemplate.opsForList().set("listKey7", 0, "listKey7_attach1_value");
    
            //修改:将链表key进行剪切,从指定的索引处开始到指定索引处结束
            redisTemplate.opsForList().rightPushAll("listKey7", "listKey7_value", "listKey7_attach1_value", "listKey7_attach2_value");
            redisTemplate.opsForList().trim("listKey7", 0, 1);
    
            //查询:获取指定key和索引处的元素
            redisTemplate.opsForList().rightPushAll("listKey8", "listKey8_value", "listKey8_attach1_value", "listKey8_attach2_value");
            String listKey8IndexValues = (String)redisTemplate.opsForList().index("listKey8", 0);
            System.out.println(listKey8IndexValues);
    
            //查询:获取指定key和范围的元素集合 -1表示返回所有
            redisTemplate.opsForList().rightPushAll("listKey9", "listKey9_value", "listKey9_attach1_value", "listKey9_attach2_value");
            List listKey9RangeValues = redisTemplate.opsForList().range("listKey9", 0, 1);
            for (Object listKey9RangeValue : listKey9RangeValues) {
                System.out.println(listKey9RangeValue);
            }
    
            //删除:移除链表左边的第一个元素并获取到它的value值(如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止)可以设置超时时间
            redisTemplate.opsForList().rightPushAll("listKey10", "listKey10_value", "listKey10_attach1_value", "listKey10_attach2_value");
            Object listKey10PopValue = redisTemplate.opsForList().leftPop("listKey10", 10, TimeUnit.SECONDS);
            System.out.println(listKey10PopValue);
    
            //删除:移除链表右边的第一个元素并获取到它的value值(如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止)可以设置超时时间
            redisTemplate.opsForList().rightPushAll("listKey11", "listKey11_value", "listKey11_attach1_value", "listKey11_attach2_value");
            Object listKey11PopValue = redisTemplate.opsForList().rightPop("listKey11", 10, TimeUnit.SECONDS);
            System.out.println(listKey11PopValue);
    
            //删除:将一个链表的右边的第一个元素弹出放到另一个链表的左边
            redisTemplate.opsForList().rightPushAll("listKey12", "listKey12_value", "listKey12_attach1_value", "listKey12_attach2_value");
            redisTemplate.opsForList().rightPushAll("listKey13", "listKey13_value", "listKey13_attach1_value", "listKey13_attach2_value");
            Object rightPopAndLeftPushValue = redisTemplate.opsForList().rightPopAndLeftPush("listKey12", "listKey13", 10, TimeUnit.SECONDS);
            System.out.println(rightPopAndLeftPushValue);
    
            //删除:将链表中值等于value的元素删除(index=0, 删除所有值等于value的元素; index>0, 从头部开始删除第一个值等于value的元素; index<0, 从尾部开始删除第一个值等于value的元素)
            redisTemplate.opsForList().rightPushAll("listKey14", "listKey14_value", "listKey14_attach1_value", "listKey14_attach2_value");
            redisTemplate.opsForList().rightPushAll("listKey15", "listKey15_value", "listKey15_attach1_value", "listKey15_attach2_value");
            redisTemplate.opsForList().rightPushAll("listKey16", "listKey16_value", "listKey16_attach1_value", "listKey16_attach2_value");
            Long listKey14Remove = redisTemplate.opsForList().remove("listKey14", 0, "listKey14_value");
            Long listKey15Remove = redisTemplate.opsForList().remove("listKey15", 2, "listKey15_value");
            Long listKey16Remove = redisTemplate.opsForList().remove("listKey16", -3, "listKey16_value");
            System.out.println(listKey14Remove);
            System.out.println(listKey15Remove);
            System.out.println(listKey16Remove);
    
            //其他:获取到指定的key的list的长度
            redisTemplate.opsForList().rightPushAll("listKey17", "listKey17_value", "listKey17_attach1_value", "listKey17_attach2_value");
            Long listKey17Size = redisTemplate.opsForList().size("listKey17");
            System.out.println(listKey17Size);
    
        }
    
        @Test
        public void setRedisTemplateTest() {
    
            //保存:保存一个元素
            Long setKey1Length1 = redisTemplate.opsForSet().add("setKey1", "setKey1_value");
            System.out.println(setKey1Length1);
    
            //保存:批量添加元素  好像不能使用set、list集合来批量添加
            Long setKey2Length1 = redisTemplate.opsForSet().add("setKey2", "setKey2_value", "setKey2_attach1_value", "setKey2_attach2_value");
            System.out.println(setKey2Length1);
    
            //修改:没有找到修改value值的方法  可以通过先删除再保存的方式进行修改
    
            //查询:获取指定集合中的所有元素
            redisTemplate.opsForSet().add("setKey3", "setKey3_value", "setKey3_attach1_value", "setKey3_attach2_value");
            Set setKey3Values = redisTemplate.opsForSet().members("setKey3");
            for (Object setKey3Value : setKey3Values) {
                System.out.println(setKey3Value);
            }
    
            //查询:随机获取到集合中的count个元素
            redisTemplate.opsForSet().add("setKey4", "setKey4_value", "setKey4_attach1_value", "setKey4_attach2_value");
            List setKey4Values = redisTemplate.opsForSet().randomMembers("setKey4", 2);
            for (Object setKey4Value : setKey4Values) {
                System.out.println(setKey4Value);
            }
    
            //查询:获取到两个集合的交集
            redisTemplate.opsForSet().add("setKey5", "setKey5_value", "setKey5_attach1_value", "setKey5_setKey6_value");
            redisTemplate.opsForSet().add("setKey6", "setKey6_value", "setKey6_attach1_value", "setKey5_setKey6_value");
            Set set5AndSet6intersect = redisTemplate.opsForSet().intersect("setKey5", "setKey6");
            for (Object o : set5AndSet6intersect) {
                System.out.println(o);
            }
    
            //查询:获取多个集合的交集
            ArrayList arrayList1 = new ArrayList<>();
            redisTemplate.opsForSet().add("setKey7", "setKey7_value", "setKey7_attach1_value", "setKey7_setKey8_setKey9_value");
            redisTemplate.opsForSet().add("setKey8", "setKey8_value", "setKey8_attach1_value", "setKey7_setKey8_setKey9_value");
            redisTemplate.opsForSet().add("setKey9", "setKey9_value", "setKey9_attach1_value", "setKey7_setKey8_setKey9_value");
            arrayList1.add("setKey8");
            arrayList1.add("setKey9");
            Set setKey7AndSet8AndSet9Intersect = redisTemplate.opsForSet().intersect("setKey7", arrayList1);
            for (Object o : setKey7AndSet8AndSet9Intersect) {
                System.out.println(o);
            }
    
            //查询:将一个集合和一个或者多个集合的交集存储到另一个集合中
            ArrayList arrayList2 = new ArrayList<>();
            redisTemplate.opsForSet().add("setKey10", "setKey10_value", "setKey10_attach1_value", "setKey10_setKey11_setKey12_value");
            redisTemplate.opsForSet().add("setKey11", "setKey11_value", "setKey11_attach1_value", "setKey10_setKey11_setKey12_value");
            redisTemplate.opsForSet().add("setKey12", "setKey12_value", "setKey12_attach1_value", "setKey10_setKey11_setKey12_value");
            arrayList2.add("setKey11");
            arrayList2.add("setKey12");
            redisTemplate.opsForSet().intersectAndStore("setKey10", arrayList2, "setKey13");
    
            //查询:获取一个和另一个或者一个和多个集合的并集
            ArrayList arrayList3 = new ArrayList<>();
            redisTemplate.opsForSet().add("setKey14", "setKey14_value", "setKey14_attach1_value", "setKey14_setKey15_setKey16_value");
            redisTemplate.opsForSet().add("setKey15", "setKey15_value", "setKey15_attach1_value", "setKey14_setKey15_setKey16_value");
            redisTemplate.opsForSet().add("setKey16", "setKey16_value", "setKey16_attach1_value", "setKey14_setKey15_setKey16_value");
            arrayList3.add("setKey15");
            arrayList3.add("setKey16");
            Set setKey14AndSet15AndSet16Union = redisTemplate.opsForSet().union("setKey14", arrayList3);
            for (Object o : setKey14AndSet15AndSet16Union) {
                System.out.println(o);
            }
            //查询:获取一个和另一个或者一个和多个集合的并集  并将集合存储在指定Key的reids中  并返回集合长度
            Long setKey14AndSet15AndSet16Length = redisTemplate.opsForSet().unionAndStore("setKey14", arrayList3, "setKey17");
            System.out.println(setKey14AndSet15AndSet16Length);
    
            //查询:获取一个和另一个或者一个和多个集合的差集  就是第一个集合和其他集合独有的元素提取出来为一个新的集合
            ArrayList arrayList4 = new ArrayList<>();
            redisTemplate.opsForSet().add("setKey18", "setKey18_value", "setKey18_attach1_value", "setKey18_setKey19_setKey20_value");
            redisTemplate.opsForSet().add("setKey19", "setKey19_value", "setKey19_attach1_value", "setKey18_setKey19_setKey20_value");
            redisTemplate.opsForSet().add("setKey20", "setKey20_value", "setKey20_attach1_value", "setKey18_setKey19_setKey20_value");
            arrayList4.add("setKey19");
            arrayList4.add("setKey20");
            Set setKey18AndSet19AndSet20Difference = redisTemplate.opsForSet().difference("setKey18", arrayList4);
            for (Object o : setKey18AndSet19AndSet20Difference) {
                System.out.println(o);
            }
            //查询:获取一个和另一个或者一个和多个集合的差集  并将集合设置到指定key的redis中  并返回集合长度
            Long setKey18AndSet19AndSet20Length = redisTemplate.opsForSet().differenceAndStore("setKey18", arrayList4, "setKey21");
            System.out.println(setKey18AndSet19AndSet20Length);
    
            //查询:随机获取一个集合中的元素
            redisTemplate.opsForSet().add("setKey22", "setKey22_value", "setKey22_attach1_value", "setKey22_attach2_value");
            String setKey22RandomValues = (String)redisTemplate.opsForSet().randomMember("setKey22");
            System.out.println(setKey22RandomValues);
    
            //查询:获取集合中的所有元素
            redisTemplate.opsForSet().add("setKey23", "setKey23_value", "setKey23_attach1_value", "setKey23_attach2_value");
            Set setKey23Values = redisTemplate.opsForSet().members("setKey23");
            for (Object setKey23Value : setKey23Values) {
                System.out.println(setKey23Value);
            }
    
            //删除:移除指定Key中的value元素  并返回集合长度
            redisTemplate.opsForSet().add("setKey24", "setKey24_value", "setKey24_attach1_value", "setKey24_attach2_value");
            Long setKey24Length = redisTemplate.opsForSet().remove("setKey24", "setKey24_attach2_value");
            System.out.println(setKey24Length);
    
            //删除:随机删除指定key中的一个元素并返回
            redisTemplate.opsForSet().add("setKey25", "setKey25_value", "setKey25_attach1_value", "setKey25_attach2_value");
            Object setKey25Value = redisTemplate.opsForSet().pop("setKey25");
            System.out.println(setKey25Value);
    
            //其他:获取集合的大小
            redisTemplate.opsForSet().add("setKey26", "setKey26_value", "setKey26_attach1_value", "setKey26_attach2_value");
            Long setKey26Length = redisTemplate.opsForSet().size("setKey26");
            System.out.println(setKey26Length);
    
        }
    
        @Test
        public void zSetRedisTemplateTest() {
    
            //保存:保存一个一个元素到集合中  第三个参数score为排序的权值  权值越小排序越前(左)
            Boolean zSetKey1 = redisTemplate.opsForZSet().add("zSetKey1", "zSetKey1_value", 1);
            System.out.println(zSetKey1);
    
            //修改:给指定的key的value的score增加值  原来的score+新增值
            redisTemplate.opsForZSet().add("zSetKey2", "zSetKey2_value", 1);
            Double zSetKey2Score = redisTemplate.opsForZSet().incrementScore("zSetKey2", "zSetKey2_value", 5);
            System.out.println(zSetKey2Score);
    
            //查询:返回元素在集合中的排名
            redisTemplate.opsForZSet().add("zSetKey3", "zSetKey3_value", 1);
            redisTemplate.opsForZSet().add("zSetKey3", "zSetKey3_attach1_value", 2);
            redisTemplate.opsForZSet().add("zSetKey3", "zSetKey3_attach2_value", 3);
            Long zSetKey3Rank = redisTemplate.opsForZSet().rank("zSetKey3", "zSetKey3_attach2_value");
            System.out.println(zSetKey3Rank);
    
            //查询:获取集合集合给定区间的元素  -1表示查询所有
            DefaultTypedTuple objectDefaultTypedTuple1 = new DefaultTypedTuple("zSetKey4_value", 1d);
            DefaultTypedTuple objectDefaultTypedTuple2 = new DefaultTypedTuple("zSetKey4_attach1_value", 2d);
            DefaultTypedTuple objectDefaultTypedTuple3 = new DefaultTypedTuple("zSetKey4_attach2_value", 3d);
            Set> typedTuples = new HashSet<>();
            typedTuples.add(objectDefaultTypedTuple1);
            typedTuples.add(objectDefaultTypedTuple2);
            typedTuples.add(objectDefaultTypedTuple3);
            redisTemplate.opsForZSet().add("zSetKey4", typedTuples);
            Set> zSetKey4 = redisTemplate.opsForZSet().reverseRangeWithScores("zSetKey4", 1, 2);
            for (ZSetOperations.TypedTuple objectTypedTuple : zSetKey4) {
                Double score = objectTypedTuple.getScore();
                Object value = objectTypedTuple.getValue();
                System.out.println(value);
                System.out.println(score);
            }
            //查询:按照score值进行  结果按照score从小到大进行排序
            Set> zSetKey41 = redisTemplate.opsForZSet().reverseRangeWithScores("zSetKey4", 1, 2);
            for (ZSetOperations.TypedTuple objectTypedTuple : zSetKey41) {
                Double score = objectTypedTuple.getScore();
                Object value = objectTypedTuple.getValue();
                System.out.println(score);
                System.out.println(value);
            }
            //查询key对应的value值在集合中的排名
            Long zSetKey4ValueRank = redisTemplate.opsForZSet().reverseRank("zSetKey4", "zSetKey4_attach2_value");
            System.out.println(zSetKey4ValueRank);
            //获取集合的大小
            Long zSetKey4Length2 = redisTemplate.opsForZSet().size("zSetKey4");
            System.out.println(zSetKey4Length2);
            //获取指定key和value中的score值
            Double score = redisTemplate.opsForZSet().score("zSetKey4", "zSetKey4_value");
            System.out.println(score);
            
            //删除指定key的指定value值  并返回删除元素的个数
            redisTemplate.opsForZSet().add("zSetKey5", "zSetKey5_value", 1);
            redisTemplate.opsForZSet().add("zSetKey5", "zSetKey5_attach1_value", 2);
            redisTemplate.opsForZSet().add("zSetKey5", "zSetKey5_attach2_value", 3);
            Long zSetKey5Length1 = redisTemplate.opsForZSet().remove("zSetKey5", "zSetKey5_value");
            System.out.println(zSetKey5Length1);
    
        }
    
        @Test
        public void emptyRedis() {
    
            Set keys = redisTemplate.keys("*");
            redisTemplate.delete(keys);
    
        }
    
    }

    15.操作redis的一些注解的使用

    package com.zengjx.project.annotation.service.impl;
    
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import com.zengjx.project.common.Result;
    import com.zengjx.project.annotation.entity.Food;
    import com.zengjx.project.annotation.mapper.FoodMapper;
    import com.zengjx.project.annotation.service.IFoodService;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.List;
    
    /**
     * @author fastrabbit
     * @date 2021-06-11
     */
    @Service
    @Transactional(rollbackFor=Exception.class)
    public class FoodServiceImpl extends ServiceImpl implements IFoodService {
    
        @Autowired
        private FoodMapper foodMapper;
    
        @Autowired
        private IFoodService foodService;
    
        /**
         * @author fastrabbit
         * @description 根据id查询单个数据  将查询到的数据放入到redis缓存中,如果根据key值能够在redis中找到则直接返回redis中的数据不执行代码  condition为缓存条件
         * @date 2021-06-11
         */
        @Override
        @Cacheable(value = "PROJECT:ANNOTATION", key = "'FOOD:'+#food.id", condition = "#food.id>0")
        public Result getById(Food food) {
    
            Result foodResult = new Result<>();
            foodResult.setData(foodMapper.selectById(food.getId()));
            return foodResult;
    
        }
    
        /**
         * @author fastrabbit
         * @description 根据查询条件查询分页数据  将查询到的数据放入到redis缓存中,如果根据key值能够在redis中找到则直接返回redis中的数据不执行代码  condition为缓存条件
         * @date 2021-06-11
         */
        @Override
        @Cacheable(value = "PROJECT:ANNOTATION", key = "'FOOD:'+#food.page+'_'+#food.rows", condition = "#food.page>0 and #food.rows>=10")
        public Result> findListByPage(Food food) {
    
            Result> listResult = new Result<>();
            Page foodPage = new Page<>(food.getPage(), food.getRows());
            QueryWrapper foodQueryWrapper = new QueryWrapper<>();
            List records = foodMapper.selectPage(foodPage, foodQueryWrapper).getRecords();
            listResult.setData(records);
            listResult.setTotal(records.size());
            return listResult;
    
        }
    
        /**
         * @author fastrabbit
         * @description 查询所有数据  将查询到的数据放入到redis缓存中,如果根据key值能够在redis中找到则直接返回redis中的数据不执行代码
         * @date 2021-06-11
         */
        @Override
        @Cacheable(value = "PROJECT:ANNOTATION", key = "'FOOD:'+'ALL'")
        public Result> getAll() {
    
            Result> foodResult = new Result<>();
            List foods = foodMapper.selectList(null);
            foodResult.setData(foods);
            foodResult.setTotal(foods.size());
            return foodResult;
    
        }
    
        /**
         * @author fastrabbit
         * @description 新增单个数据
         * @date 2021-06-11
         */
        @Override
        public Result insert(Food food) {
    
            Result objectResult = new Result<>();
            foodMapper.insert(food);
            // 通过调用上面的getById方法将新增的数据添加到redis中
            // 因为redis注解存储的方式使用的是spring的aop动态代理所以通过注入自己的方式来使用代理类中的方法
            foodService.getById(food);
            return objectResult;
    
        }
    
        /**
         * @author fastrabbit
         * @description 修改单个数据
         * @date 2021-06-11
         */
        @Override
        public Result update(Food food) {
    
            Result objectResult = new Result<>();
            foodMapper.updateById(food);
            // 通过调用下面的redisUpdate方法将存储在redis中的数据进行更新
            // 因为redis注解存储的方式使用的是spring的aop动态代理所以通过注入自己的方式来使用代理类中的方法
            Result byId = foodService.redisUpdate(food);
            Food data = byId.getData();
            System.out.println(data);
            return objectResult;
    
        }
    
        /**
         * @author fastrabbit
         * @Description 修改redis缓存中的数据  @CachePut注解:一定会执行代码然后将返回数据存放在redis中,保证数据库和redis中的数据一致性
         * @Date 13:38 2021/6/11
         */
        @Override
        @CachePut(value = "PROJECT:ANNOTATION", key = "'FOOD:'+#food.id", condition = "#food.id>0")
        public Result redisUpdate(Food food) {
    
            Result foodResult = new Result<>();
            foodResult.setData(foodMapper.selectById(food.getId()));
            return foodResult;
    
        }
    
        /**
         * @author fastrabbit
         * @description 删除单个数据  @CacheEvict:当执行到该方法时会根据key将redis中的数据进行删除,具有多项配置
         * @date 2021-06-11
         */
        @Override
        @CacheEvict(value = "PROJECT:ANNOTATION", key = "'FOOD:'+#food.id", condition = "#food.id>0")
        public Result delete(Food food) {
    
            Result objectResult = new Result<>();
            foodMapper.deleteById(food.getId());
            return objectResult;
    
        }
    
    }                        
                                                    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
                                                    
    作者最新文章
    编程开发
    相关文章 更多
    精品专题 更多
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    macOS软件

    正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

    IOS软件

    正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

    AI

    正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

    Mac软件 更多
    Aperty macOS版
    Aperty macOS版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw macOS版
    AionClaw macOS版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy macOS版
    Loomy macOS版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirBuddy 3 macOS版
    AirBuddy 3 macOS版

    AirBuddy 3 是面向 macOS 的蓝牙外设增强工具,可集中查看 AirPods、Beats 与苹果设备电量,提供快速连接、播放控制、电量提醒、桌面小组件和多台 Mac 外设接力等功能。

    AirServer macOS版
    AirServer macOS版

    AirServer macOS版可把 Mac 转换为无线投屏接收端,通过 AirPlay 或 Google Cast 接收手机、平板和电脑画面,并支持多设备同时连接、高清镜像及会话录制,适合家庭娱乐、课堂教学、会议演示和应用展示。

    AnyDesk macOS版
    AnyDesk macOS版

    AnyDesk macOS版是一款适用于远程办公、设备维护和客户支持的远程桌面工具,可连接并操作异地计算机,支持文件传输、无人值守访问、会话权限控制及跨平台协作。

    WINDOWS 更多
    讯飞绘文 网页版
    讯飞绘文 网页版

    讯飞绘文网页版是科大讯飞推出的AI图文创作与内容运营工具,覆盖热点选题、文章生成、稿件校对、智能配图、排版发布和数据复盘等环节,适合自媒体创作者及内容团队在线使用。

    Maya(Autodesk Maya) Windows版
    Maya(Autodesk Maya) Windows版

    Autodesk Maya 是面向影视、电视、动画和游戏行业的专业三维制作软件,集多边形与 NURBS 建模、角色绑定、关键帧和动作捕捉动画、Bifrost 特效模拟、材质开发及 Arnold 渲染于一体,

    Aperty Windows版
    Aperty Windows版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw Windows版
    AionClaw Windows版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy Windows版
    Loomy Windows版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirServer Windows版
    AirServer Windows版

    AirServer Windows版可把电脑变成AirPlay、Google Cast和Miracast无线投屏接收端,适合会议演示、课堂教学及家庭大屏分享。发送设备通常无需另装客户端,并可同时接收和智能排列多个镜像会话。

    即将离开本站
    您即将前往第三方网站,请确认是否继续?

    网站备案号:苏ICP备2026018738号-1 联系邮箱:bd@zhengruan.com

    Copyright ©2018-2026