1.필요한 jar 패키지를 .pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>springboot_redis_demo</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.0</version> </parent> <dependencies> <!--web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.5.0</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> <!--jdbc--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> <version>2.5.0</version> </dependency> <!--druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.6</version> </dependency> <!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3</version> </dependency> <!--generator--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency> <!--freemarker--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> <version>2.5.0</version> </dependency> <!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.5.0</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> <scope>provided</scope> </dependency> <!--springboot-test--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>2.5.0</version> <scope>test</scope> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <!--swagger2--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0</version> </dependency> <!--swagger-ui--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>3.0.0</version> </dependency> </dependencies> </project>
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; </#if> import java.util.List; <#if superControllerClassPackage??> import ${superControllerClassPackage}; </#if> /** * @author ${author} * @date ${date} */ @Api(tags = {"${table.comment!}"}) <#if restControllerStyle> @RestController <#else> @Controller </#if> @RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>") <#if kotlin> class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if> <#else> <#if superControllerClass??> public class ${table.controllerName} extends ${superControllerClass} { <#else> public class ${table.controllerName} { </#if> 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<List<${entity}>> 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<List<${entity}>> getAll(){ return ${(table.serviceName?substring(1))?uncap_first}.getAll(); } /** * @author fastrabbit * @description 新增单个数据 * @date ${date} */ @ApiOperation(value = "新增单个数据") @RequestMapping(value = "/insert", method = RequestMethod.POST) public Result<Object> 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<Object> 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<Object> update(@RequestBody ${entity} ${entity?uncap_first}){ return ${(table.serviceName?substring(1))?uncap_first}.update(${entity?uncap_first}); } } </#if>
6.mybatisplus 템플릿——entity
package ${package.Entity}; <#list table.importPackages as pkg> import ${pkg}; </#list> <#if swagger2> import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; </#if> import ${cfg.packagePath}.common.BaseQuery; <#if entityLombokModel> import lombok.Data; import lombok.EqualsAndHashCode; <#if chainModel> import lombok.experimental.Accessors; </#if> </#if> /** * @author ${author} * @date ${date} */ <#if entityLombokModel> @Data <#if superEntityClass??> @EqualsAndHashCode(callSuper = true) <#else> @EqualsAndHashCode(callSuper = false) </#if> <#if chainModel> @Accessors(chain = true) </#if> </#if> <#if table.convert> @TableName("${table.name}") </#if> <#if swagger2> @ApiModel(value="${entity}对象", description="${table.comment!}") </#if> <#if superEntityClass??> public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> { <#elseif activeRecord> public class ${entity} extends Model<${entity}> { <#else> public class ${entity} extends BaseQuery implements Serializable { </#if> <#if entitySerialVersionUID> private static final long serialVersionUID = 1L; </#if> <#-- ---------- BEGIN 字段循环遍历 ----------> <#list table.fields as field> <#if field.keyFlag> <#assign keyPropertyName="${field.propertyName}"/> </#if> <#if field.comment!?length gt 0> <#if swagger2> @ApiModelProperty(value = "${field.comment}") <#else> /** * ${field.comment} */ </#if> </#if> <#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}") </#if> <#-- 普通字段 --> <#elseif field.fill??> <#-- ----- 存在字段填充设置 -----> <#if field.convert> @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill}) <#else> @TableField(fill = FieldFill.${field.fill}) </#if> <#elseif field.convert> @TableField("${field.annotationColumnName}") </#if> <#-- 乐观锁注解 --> <#if (versionFieldName!"") == field.name> @Version </#if> <#-- 逻辑删除注解 --> <#if (logicDeleteFieldName!"") == field.name> @TableLogic </#if> private ${field.propertyType} ${field.propertyName}; </#list> <#------------ END 字段循环遍历 ----------> <#if !entityLombokModel> <#list table.fields as field> <#if field.propertyType == "boolean"> <#assign getprefix="is"/> <#else> <#assign getprefix="get"/> </#if> 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}) { </#if> this.${field.propertyName} = ${field.propertyName}; <#if chainModel> return this; </#if> } </#list> </#if> <#if entityColumnConstant> <#list table.fields as field> public static final String ${field.name?upper_case} = "${field.name}"; </#list> </#if> <#if activeRecord> @Override protected Serializable pkVal() { <#if keyPropertyName??> return this.${keyPropertyName}; <#else> return null; </#if> } </#if> <#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} + </#if> </#list> "}"; } </#if> }
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}> { } </#if>
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<T> { /** * 是否成功 默认为成功 */ 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<List<${entity}>> findListByPage(${entity} ${entity?uncap_first}); /** * @author fastrabbit * @description 查询所有数据 * @date ${date} */ Result<List<${entity}>> getAll(); /** * @author fastrabbit * @description 新增单个数据 * @date ${date} */ Result<Object> insert(${entity} ${entity?uncap_first}); /** * @author fastrabbit * @description 修改单个数据 * @date ${date} */ Result<Object> update(${entity} ${entity?uncap_first}); /** * @author fastrabbit * @description 删除单个数据 * @date ${date} */ Result<Object> delete(${entity} ${entity?uncap_first}); } </#if>
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<List<${entity}>> findListByPage(Food food) { Result<List<${entity}>> 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<List<${entity}>> getAll() { Result<List<${entity}>> 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<Object> insert(Food food) { Result<Object> objectResult = new Result<>(); foodMapper.insert(food); return objectResult; } /** * @author fastrabbit * @description 修改单个数据 * @date ${date} */ @Override public Result<Object> update(Food food) { Result<Object> objectResult = new Result<>(); foodMapper.updateById(food); return objectResult; } /** * @author fastrabbit * @description 删除单个数据 * @date ${date} */ @Override public Result<Object> delete(Food food) { Result<Object> objectResult = new Result<>(); foodMapper.deleteById(food.getId()); return objectResult; } } </#if>
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 { /** * <p> * 读取控制台内容 * </p> */ 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<String, Object> map = new HashMap<>(); List<TableInfo> 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<FileOutConfig> 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<String, Object>中的key和value进行序列化 * @param: RedisConnectionFactory * @return: RedisTemplate<String, Object> * @author: fastrabbit * @date: 2021/6/11 9:12 */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String> keys ArrayList<String> arrayListKeys = new ArrayList<>(); arrayListKeys.add("stringKey1"); arrayListKeys.add("stringKey2"); arrayListKeys.add("stringKey3"); List<Object> 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<String> allKeys = redisTemplate.keys("*"); Set<String> somekeys = redisTemplate.keys("stringKey?"); Set<String> 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<String> 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<String, Object> 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<Object, Object> getSpecifyMap = redisTemplate.opsForHash().entries("hashKey5"); for (Object o : getSpecifyMap.keySet()) { System.out.println(o); System.out.println(getSpecifyMap.get(o)); } //查询:获取指定hashkey中的所有field字段 HashMap<String, Object> 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<Object> getSpecifySet = redisTemplate.opsForHash().keys("hashKey6"); for (Object o : getSpecifySet) { System.out.println(o); } //查询:获取到指定hashKey的field的数量 HashMap<String, Object> 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<String, Object> 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<Object> 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<T> 参数泛型需要和设置的模板的泛型一致,不然保存的是数组而不是数组元素 redisTemplate.opsForList().rightPush("listKey2", "listKey2_value"); ArrayList<Object> 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<T> redisTemplate.opsForList().leftPush("listKey4", "listKey4_value"); ArrayList<Object> 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<Object> 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<Object> 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<Object> 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<Object> set5AndSet6intersect = redisTemplate.opsForSet().intersect("setKey5", "setKey6"); for (Object o : set5AndSet6intersect) { System.out.println(o); } //查询:获取多个集合的交集 ArrayList<String> 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<Object> setKey7AndSet8AndSet9Intersect = redisTemplate.opsForSet().intersect("setKey7", arrayList1); for (Object o : setKey7AndSet8AndSet9Intersect) { System.out.println(o); } //查询:将一个集合和一个或者多个集合的交集存储到另一个集合中 ArrayList<String> 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<String> 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<Object> 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<String> 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<Object> 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<Object> 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<Object> objectDefaultTypedTuple1 = new DefaultTypedTuple<Object>("zSetKey4_value", 1d); DefaultTypedTuple<Object> objectDefaultTypedTuple2 = new DefaultTypedTuple<Object>("zSetKey4_attach1_value", 2d); DefaultTypedTuple<Object> objectDefaultTypedTuple3 = new DefaultTypedTuple<Object>("zSetKey4_attach2_value", 3d); Set<ZSetOperations.TypedTuple<Object>> typedTuples = new HashSet<>(); typedTuples.add(objectDefaultTypedTuple1); typedTuples.add(objectDefaultTypedTuple2); typedTuples.add(objectDefaultTypedTuple3); redisTemplate.opsForZSet().add("zSetKey4", typedTuples); Set<ZSetOperations.TypedTuple<Object>> zSetKey4 = redisTemplate.opsForZSet().reverseRangeWithScores("zSetKey4", 1, 2); for (ZSetOperations.TypedTuple<Object> objectTypedTuple : zSetKey4) { Double score = objectTypedTuple.getScore(); Object value = objectTypedTuple.getValue(); System.out.println(value); System.out.println(score); } //查询:按照score值进行 结果按照score从小到大进行排序 Set<ZSetOperations.TypedTuple<Object>> zSetKey41 = redisTemplate.opsForZSet().reverseRangeWithScores("zSetKey4", 1, 2); for (ZSetOperations.TypedTuple<Object> 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<String> 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<FoodMapper, Food> 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<Food> getById(Food food) { Result<Food> 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<List<Food>> findListByPage(Food food) { Result<List<Food>> listResult = new Result<>(); Page<Food> foodPage = new Page<>(food.getPage(), food.getRows()); QueryWrapper<Food> foodQueryWrapper = new QueryWrapper<>(); List<Food> 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<List<Food>> getAll() { Result<List<Food>> foodResult = new Result<>(); List<Food> foods = foodMapper.selectList(null); foodResult.setData(foods); foodResult.setTotal(foods.size()); return foodResult; } /** * @author fastrabbit * @description 新增单个数据 * @date 2021-06-11 */ @Override public Result<Object> insert(Food food) { Result<Object> 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<Object> update(Food food) { Result<Object> objectResult = new Result<>(); foodMapper.updateById(food); // 通过调用下面的redisUpdate方法将存储在redis中的数据进行更新 // 因为redis注解存储的方式使用的是spring的aop动态代理所以通过注入自己的方式来使用代理类中的方法 Result<Food> 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<Food> redisUpdate(Food food) { Result<Food> 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<Object> delete(Food food) { Result<Object> objectResult = new Result<>(); foodMapper.deleteById(food.getId()); return objectResult; } }운영을 위한 몇 가지 주석
위 내용은 springboot+mybatisplus+redis 데모 구현 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

redisoutperformstraditionaldatabasesinspeedforread/writeoperationsduetoitsin-memorynature, whiletraditionaldatabasesexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexexceleclexquer

useredisinsteadofatraditionaldatabasewhenyorapplicationrequiresspeedandreal-timedataprocessing, suchasforcaching, sessionmanagement, orreal-timeanalytics.rediesxcelsin : 1) Caching, Retoadon-PrimaryDatabases; 2) 세션 관리, 단순화 datahandlon

Redis는 고성능과 유연성으로 인해 SQL 데이터베이스를 뛰어 넘습니다. 1) Redis는 메모리 스토리지를 통해 매우 빠른 읽기 및 쓰기 속도를 달성합니다. 2) 복잡한 데이터 처리에 적합한 목록 및 컬렉션과 같은 다양한 데이터 구조를 지원합니다. 3) 단일 스레드 모델은 개발을 단순화하지만 높은 동시성은 병목 현상이 될 수 있습니다.

Redis는 동시성이 높은 기존 데이터베이스보다 우수하고 대기 시간 시나리오가 낮지 만 복잡한 쿼리 및 트랜잭션 처리에는 적합하지 않습니다. 1.Redis는 메모리 저장, 빠른 읽기 및 쓰기 속도, 높은 동시성 및 낮은 대기 시간 요구 사항에 적합합니다. 2. 전통적인 데이터베이스는 디스크를 기반으로하며 복잡한 쿼리 및 트랜잭션 처리를 지원하며 데이터 일관성과 지속성이 강합니다. 3. Redis는 기존 데이터베이스의 보충 또는 대체물로 적합하지만 특정 비즈니스 요구에 따라 선택해야합니다.

redisisahigh-performancein-memorydatrscructurestorestorethexcelscelsspeedandversitility

Redis는 주로 데이터베이스이지만 단순한 데이터베이스 이상입니다. 1. 데이터베이스로서 Redis는 지속성을 지원하고 고성능 요구에 적합합니다. 2. 캐시로서 Redis는 응용 프로그램 응답 속도를 향상시킵니다. 3. 메시지 중개인으로서 Redis는 실시간 커뮤니케이션에 적합한 Publish-Subscribe 모드를 지원합니다.

redisiSamultifacetedToolthatservesAsadatabase, Server 및 more.ItfunctionsAnin-memoryDatrastRuctureStore, SupportSvariousDatastructures, andCanbeusedAsacache, MessageBroker, SessionStorage, 및 FordiptributedLocking을 지원합니다.

redisisanopen-source, in-memorydatructurestorestoreusedasadatabase, cache 및 messagebroker, excell


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

Dreamweaver Mac版
시각적 웹 개발 도구