您好,登錄后才能下訂單哦!
今天小編給大家分享一下springboot+mybatisplus+redis的demo怎么實現的相關知識點,內容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
1.pom.xml中倒入需要的jar包
<?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的demo怎么實現”這篇文章的所有內容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。