springboot+mybatisplus+redis的demo怎么实现
springboot+mybatisplus+redis的demo怎么实现
今天小编给大家分享一下springboot+mybatisplus+redis的demo怎么实现的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
1.pom.xml中倒入需要的jar包
<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="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.0http://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.Driverurl:jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8&useSSL=falseusername:rootpassword:123456type:com.alibaba.druid.pool.DruidDataSource#配置redisredis:host:127.0.0.1port:6379database:0password:123456
3.启动类需要的注解
packagecom.zengjx.project;importorg.mybatis.spring.annotation.MapperScan;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.cache.annotation.EnableCaching;/***@authorfastrabbit*@date2021/6/99:43*/@SpringBootApplication@EnableCaching@MapperScan("com.zengjx.project.*.mapper")publicclassRedisApp{publicstaticvoidmain(String[]args){SpringApplication.run(RedisApp.class,args);}}
4.mybatisplus模板——baseQuery
package${cfg.packagePath}.common;importcom.baomidou.mybatisplus.annotation.TableField;importlombok.Data;/***@author${author}*@date${date}*/@DatapublicclassBaseQuery{/***当前页数默认为1*/@TableField(exist=false)privateIntegerpage=1;/***每页数据量默认为10*/@TableField(exist=false)privateIntegerrows=10;}
5.mybatisplus模板——controller
package${package.Controller};import${cfg.packagePath}.common.Result;import${package.Entity}.${entity};import${package.Service}.${table.serviceName};importio.swagger.annotations.Api;importio.swagger.annotations.ApiOperation;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.RequestBody;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;<#ifrestControllerStyle>importorg.springframework.web.bind.annotation.RestController;<#else>importorg.springframework.stereotype.Controller;</#if>importjava.util.List;<#ifsuperControllerClassPackage??>import${superControllerClassPackage};</#if>/***@author${author}*@date${date}*/@Api(tags={"${table.comment!}"})<#ifrestControllerStyle>@RestController<#else>@Controller</#if>@RequestMapping("<#ifpackage.ModuleName??&&package.ModuleName!="">/${package.ModuleName}</#if>/<#ifcontrollerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")<#ifkotlin>class${table.controllerName}<#ifsuperControllerClass??>:${superControllerClass}()</#if><#else><#ifsuperControllerClass??>publicclass${table.controllerName}extends${superControllerClass}{<#else>publicclass${table.controllerName}{</#if>privateLoggerlogger=LoggerFactory.getLogger(getClass());@Autowiredprivate${table.serviceName}${(table.serviceName?substring(1))?uncap_first};/***@authorfastrabbit*@description根据id查询单个数据*@date${date}*/@ApiOperation(value="根据id查询单个数据")@RequestMapping(value="/getById")publicResult<${entity}>getById(@RequestBody${entity}${entity?uncap_first}){return${(table.serviceName?substring(1))?uncap_first}.getById(${entity?uncap_first});}/***@authorfastrabbit*@description根据查询条件查询分页数据*@date${date}*/@ApiOperation(value="根据查询条件查询分页数据")@RequestMapping(value="/list")publicResult<List<${entity}>>findListByPage(@RequestBody${entity}${entity?uncap_first}){return${(table.serviceName?substring(1))?uncap_first}.findListByPage(${entity?uncap_first});}/***@authorfastrabbit*@description查询所有数据*@date${date}*/@ApiOperation(value="查询所有数据")@RequestMapping(value="/getAll")publicResult<List<${entity}>>getAll(){return${(table.serviceName?substring(1))?uncap_first}.getAll();}/***@authorfastrabbit*@description新增单个数据*@date${date}*/@ApiOperation(value="新增单个数据")@RequestMapping(value="/insert",method=RequestMethod.POST)publicResult<Object>insert(@RequestBody${entity}${entity?uncap_first}){return${(table.serviceName?substring(1))?uncap_first}.insert(${entity?uncap_first});}/***@authorfastrabbit*@description删除单个数据*@date${date}*/@ApiOperation(value="删除单个数据")@RequestMapping(value="/delete")publicResult<Object>delete(@RequestBody${entity}${entity?uncap_first}){return${(table.serviceName?substring(1))?uncap_first}.delete(${entity?uncap_first});}/***@authorfastrabbit*@description修改单个数据*@date${date}*/@ApiOperation(value="修改单个数据")@RequestMapping(value="/update",method=RequestMethod.POST)publicResult<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};<#listtable.importPackagesaspkg>import${pkg};</#list><#ifswagger2>importio.swagger.annotations.ApiModel;importio.swagger.annotations.ApiModelProperty;</#if>import${cfg.packagePath}.common.BaseQuery;<#ifentityLombokModel>importlombok.Data;importlombok.EqualsAndHashCode;<#ifchainModel>importlombok.experimental.Accessors;</#if></#if>/***@author${author}*@date${date}*/<#ifentityLombokModel>@Data<#ifsuperEntityClass??>@EqualsAndHashCode(callSuper=true)<#else>@EqualsAndHashCode(callSuper=false)</#if><#ifchainModel>@Accessors(chain=true)</#if></#if><#iftable.convert>@TableName("${table.name}")</#if><#ifswagger2>@ApiModel(value="${entity}对象",description="${table.comment!}")</#if><#ifsuperEntityClass??>publicclass${entity}extends${superEntityClass}<#ifactiveRecord><${entity}></#if>{<#elseifactiveRecord>publicclass${entity}extendsModel<${entity}>{<#else>publicclass${entity}extendsBaseQueryimplementsSerializable{</#if><#ifentitySerialVersionUID>privatestaticfinallongserialVersionUID=1L;</#if><#------------BEGIN字段循环遍历----------><#listtable.fieldsasfield><#iffield.keyFlag><#assignkeyPropertyName="${field.propertyName}"/></#if><#iffield.comment!?lengthgt0><#ifswagger2>@ApiModelProperty(value="${field.comment}")<#else>/***${field.comment}*/</#if></#if><#iffield.keyFlag><#--主键--><#iffield.keyIdentityFlag>@TableId(value="${field.annotationColumnName}",type=IdType.AUTO)<#elseifidType??>@TableId(value="${field.annotationColumnName}",type=IdType.${idType})<#elseiffield.convert>@TableId("${field.annotationColumnName}")</#if><#--普通字段--><#elseiffield.fill??><#-------存在字段填充设置-----><#iffield.convert>@TableField(value="${field.annotationColumnName}",fill=FieldFill.${field.fill})<#else>@TableField(fill=FieldFill.${field.fill})</#if><#elseiffield.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><#listtable.fieldsasfield><#iffield.propertyType=="boolean"><#assigngetprefix="is"/><#else><#assigngetprefix="get"/></#if>public${field.propertyType}${getprefix}${field.capitalName}(){return${field.propertyName};}<#ifchainModel>public${entity}set${field.capitalName}(${field.propertyType}${field.propertyName}){<#else>publicvoidset${field.capitalName}(${field.propertyType}${field.propertyName}){</#if>this.${field.propertyName}=${field.propertyName};<#ifchainModel>returnthis;</#if>}</#list></#if><#ifentityColumnConstant><#listtable.fieldsasfield>publicstaticfinalString${field.name?upper_case}="${field.name}";</#list></#if><#ifactiveRecord>@OverrideprotectedSerializablepkVal(){<#ifkeyPropertyName??>returnthis.${keyPropertyName};<#else>returnnull;</#if>}</#if><#if!entityLombokModel>@OverridepublicStringtoString(){return"${entity}{"+<#listtable.fieldsasfield><#iffield_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}*/<#ifkotlin>interface${table.mapperName}:${superMapperClass}<${entity}><#else>publicinterface${table.mapperName}extends${superMapperClass}<${entity}>{}</#if>
8.mybatisplus模板——mybatisplusConfig
package${cfg.packagePath}.globalconfig;importcom.baomidou.mybatisplus.annotation.DbType;importcom.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;importcom.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.transaction.annotation.EnableTransactionManagement;/***@author${author}*@date${date}*/@Configuration@EnableTransactionManagementpublicclassMybatisPlusConfig{/***@authorfastrabbit*@description获取分页插件*@date${date}*/@BeanpublicMybatisPlusInterceptormybatisPlusInterceptor(){MybatisPlusInterceptorinterceptor=newMybatisPlusInterceptor();interceptor.addInnerInterceptor(newPaginationInnerInterceptor(DbType.H2));returninterceptor;}}
9.mybatisplus模板——result
package${cfg.packagePath}.common;importlombok.Data;/***@author${author}*@date${date}*/@DatapublicclassResult<T>{/***是否成功默认为成功*/privateBooleansuccess=true;/***状态码默认为200*/privateIntegercode=200;/***返回信息描述*/privateStringmessage;/***返回数据*/privateTdata;/***返回数据量*/privateIntegertotal;}
10.mybatisplus模板——service
package${package.Service};import${superServiceClassPackage};import${cfg.packagePath}.common.Result;import${package.Entity}.${entity};importjava.util.List;/***@author${author}*@date${date}*/<#ifkotlin>interface${table.serviceName}:${superServiceClass}<${entity}><#else>publicinterface${table.serviceName}extends${superServiceClass}<${entity}>{/***@authorfastrabbit*@description根据id查询单个数据*@date${date}*/Result<${entity}>getById(${entity}${entity?uncap_first});/***@authorfastrabbit*@description根据查询条件查询分页数据*@date${date}*/Result<List<${entity}>>findListByPage(${entity}${entity?uncap_first});/***@authorfastrabbit*@description查询所有数据*@date${date}*/Result<List<${entity}>>getAll();/***@authorfastrabbit*@description新增单个数据*@date${date}*/Result<Object>insert(${entity}${entity?uncap_first});/***@authorfastrabbit*@description修改单个数据*@date${date}*/Result<Object>update(${entity}${entity?uncap_first});/***@authorfastrabbit*@description删除单个数据*@date${date}*/Result<Object>delete(${entity}${entity?uncap_first});}</#if>
11.mybatisplus模板——serviceImpl
package${package.ServiceImpl};importcom.baomidou.mybatisplus.core.conditions.query.QueryWrapper;importcom.baomidou.mybatisplus.extension.plugins.pagination.Page;importcom.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};importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Transactional;importjava.util.List;/***@author${author}*@date${date}*/@Service@Transactional(rollbackFor=Exception.class)<#ifkotlin>openclass${table.serviceImplName}:${superServiceImplClass}<${table.mapperName},${entity}>(),${table.serviceName}{}<#else>publicclass${table.serviceImplName}extends${superServiceImplClass}<${table.mapperName},${entity}>implements${table.serviceName}{@Autowiredprivate${table.mapperName}${table.mapperName?uncap_first};/***@authorfastrabbit*@description根据id查询单个数据*@date${date}*/@OverridepublicResult<${entity}>getById(Foodfood){Result<${entity}>foodResult=newResult<>();foodResult.setData(foodMapper.selectById(food.getId()));returnfoodResult;}/***@authorfastrabbit*@description根据查询条件查询分页数据*@date${date}*/@OverridepublicResult<List<${entity}>>findListByPage(Foodfood){Result<List<${entity}>>listResult=newResult<>();Page<${entity}>foodPage=newPage<>(food.getPage(),food.getRows());QueryWrapper<${entity}>foodQueryWrapper=newQueryWrapper<>();List<${entity}>records=foodMapper.selectPage(foodPage,foodQueryWrapper).getRecords();listResult.setData(records);listResult.setTotal(records.size());returnlistResult;}/***@authorfastrabbit*@description查询所有数据*@date${date}*/@OverridepublicResult<List<${entity}>>getAll(){Result<List<${entity}>>foodResult=newResult<>();List<${entity}>foods=foodMapper.selectList(null);foodResult.setData(foods);foodResult.setTotal(foods.size());returnfoodResult;}/***@authorfastrabbit*@description新增单个数据*@date${date}*/@OverridepublicResult<Object>insert(Foodfood){Result<Object>objectResult=newResult<>();foodMapper.insert(food);returnobjectResult;}/***@authorfastrabbit*@description修改单个数据*@date${date}*/@OverridepublicResult<Object>update(Foodfood){Result<Object>objectResult=newResult<>();foodMapper.updateById(food);returnobjectResult;}/***@authorfastrabbit*@description删除单个数据*@date${date}*/@OverridepublicResult<Object>delete(Foodfood){Result<Object>objectResult=newResult<>();foodMapper.deleteById(food.getId());returnobjectResult;}}</#if>
12.mybatisplus模板代码生成器——CodeGenerator
packagecom.zengjx.project;importcom.baomidou.mybatisplus.core.exceptions.MybatisPlusException;importcom.baomidou.mybatisplus.core.toolkit.StringPool;importcom.baomidou.mybatisplus.core.toolkit.StringUtils;importcom.baomidou.mybatisplus.generator.AutoGenerator;importcom.baomidou.mybatisplus.generator.InjectionConfig;importcom.baomidou.mybatisplus.generator.config.*;importcom.baomidou.mybatisplus.generator.config.po.TableInfo;importcom.baomidou.mybatisplus.generator.config.rules.NamingStrategy;importcom.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;importjava.io.File;importjava.util.*;/***@authorfastrabbit*@date2021/5/259:28*/publicclassCodeGenerator{/***<p>*读取控制台内容*</p>*/publicstaticStringscanner(Stringtip){Scannerscanner=newScanner(System.in);StringBuilderhelp=newStringBuilder();help.append("请输入"+tip+":");System.out.println(help.toString());if(scanner.hasNext()){Stringipt=scanner.next();if(StringUtils.isNotBlank(ipt)){returnipt;}}thrownewMybatisPlusException("请输入正确的"+tip+"!");}publicstaticvoidmain(String[]args){//代码生成器AutoGeneratormpg=newAutoGenerator();//全局配置GlobalConfiggc=newGlobalConfig();//获取到当前项目的根目录StringprojectPath=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);//XMLResultMap:mapper.xml生成查询映射结果gc.setBaseResultMap(true);//是否覆盖原来的文件gc.setFileOverride(false);mpg.setGlobalConfig(gc);//======================================================================================================================//数据源配置DataSourceConfigdsc=newDataSourceConfig();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);//======================================================================================================================//包配置PackageConfigpc=newPackageConfig();pc.setModuleName(scanner("模块名"));//设置包的路径该路径为com.公司名.项目名StringpackagePath="com.zengjx.project";pc.setParent(packagePath);mpg.setPackageInfo(pc);//======================================================================================================================//自定义配置InjectionConfigcfg=newInjectionConfig(){@OverridepublicvoidinitMap(){Map<String,Object>map=newHashMap<>();List<TableInfo>tableInfoList=this.getConfig().getTableInfoList();for(TableInfotableInfo:tableInfoList){//项目包的路径使用到的类有BaseQuery、MybatisPlusConfig、Resultmap.put("packagePath",packagePath);}this.setMap(map);}};//======================================================================================================================//如果模板引擎是freemarkerStringtemplatePath="/templates/mapper.xml.ftl";//如果模板引擎是velocity//StringtemplatePath="/templates/mapper.xml.vm";//自定义输出配置List<FileOutConfig>focList=newArrayList<>();//自定义配置会被优先输出这是一个示例focList.add(newFileOutConfig(templatePath){@OverridepublicStringoutputFile(TableInfotableInfo){//自定义输出文件名,如果你Entity设置了前后缀、此处注意xml的名称会跟着发生变化!!//指定xml文件输出位置returnprojectPath+"/src/main/resources/com/zengjx/project/"+pc.getModuleName()+"/mapper"+"/"+tableInfo.getEntityName()+"Mapper"+StringPool.DOT_XML;}});//自定义controller的代码模板templatePath="/templates/controller.java.ftl";//自定义配置会被优先输出focList.add(newFileOutConfig(templatePath){@OverridepublicStringoutputFile(TableInfotableInfo){//自定义输出文件名+pc.getModuleName()Stringexpand=projectPath+"/src/main/java/com/zengjx/project/"+pc.getModuleName()+"/"+"controller";returnString.format((expand+File.separator+"%s"+".java"),tableInfo.getControllerName());}});//自定义entity的代码模板templatePath="/templates/entity.java.ftl";//自定义配置会被优先输出focList.add(newFileOutConfig(templatePath){@OverridepublicStringoutputFile(TableInfotableInfo){//自定义输出文件名+pc.getModuleName()Stringexpand=projectPath+"/src/main/java/com/zengjx/project/"+pc.getModuleName()+"/"+"entity";returnString.format((expand+File.separator+"%s"+".java"),tableInfo.getEntityName());}});//自定义service的代码模板templatePath="/templates/service.java.ftl";//自定义配置会被优先输出focList.add(newFileOutConfig(templatePath){@OverridepublicStringoutputFile(TableInfotableInfo){//自定义输出文件名+pc.getModuleName()Stringexpand=projectPath+"/src/main/java/com/zengjx/project/"+pc.getModuleName()+"/"+"service";returnString.format((expand+File.separator+"%s"+".java"),tableInfo.getServiceName());}});//自定义BaseQuery代码模板templatePath="/templates/baseQuery.java.ftl";//自定义配置会被优先输出focList.add(newFileOutConfig(templatePath){@OverridepublicStringoutputFile(TableInfotableInfo){//自定义输出文件名+pc.getModuleName()Stringexpand=projectPath+"/src/main/java/com/zengjx/project/"+"common";returnString.format((expand+File.separator+"%s"+".java"),"BaseQuery");}});//自定义Result代码模板templatePath="/templates/result.java.ftl";//自定义配置会被优先输出focList.add(newFileOutConfig(templatePath){@OverridepublicStringoutputFile(TableInfotableInfo){//自定义输出文件名+pc.getModuleName()Stringexpand=projectPath+"/src/main/java/com/zengjx/project/"+"common";returnString.format((expand+File.separator+"%s"+".java"),"Result");}});//自定义全局MybatisPlusConfig代码模板templatePath="/templates/mybatisPlusConfig.java.ftl";//自定义配置会被优先输出focList.add(newFileOutConfig(templatePath){@OverridepublicStringoutputFile(TableInfotableInfo){//自定义输出文件名+pc.getModuleName()Stringexpand=projectPath+"/src/main/java/com/zengjx/project/"+"globalconfig";returnString.format((expand+File.separator+"%s"+".java"),"MybatisPlusConfig");}});//======================================================================================================================cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);//配置模板TemplateConfigtemplateConfig=newTemplateConfig();//配置自定义输出模板//指定自定义模板路径,注意不要带上.ftl/.vm,会根据使用的模板引擎自动识别//templateConfig.setEntity("templates/entity2.java");//templateConfig.setService();//templateConfig.setController();templateConfig.setXml(null);mpg.setTemplate(templateConfig);//======================================================================================================================//策略配置StrategyConfigstrategy=newStrategyConfig();//数据库表映射到实体的命名策略下划线转驼峰命名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(newFreemarkerTemplateEngine());//执行mpg.execute();}}
13.redis的配置文件
packagecom.zengjx.project.globalconfig;importcom.fasterxml.jackson.annotation.JsonAutoDetect;importcom.fasterxml.jackson.annotation.JsonTypeInfo;importcom.fasterxml.jackson.annotation.PropertyAccessor;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;importorg.springframework.cache.annotation.CachingConfigurerSupport;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.data.redis.cache.RedisCacheConfiguration;importorg.springframework.data.redis.cache.RedisCacheManager;importorg.springframework.data.redis.cache.RedisCacheWriter;importorg.springframework.data.redis.connection.RedisConnectionFactory;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;importorg.springframework.data.redis.serializer.RedisSerializationContext;importorg.springframework.data.redis.serializer.StringRedisSerializer;/***@authorfastrabbit*@date2021/6/99:55*/@ConfigurationpublicclassRedisConfigextendsCachingConfigurerSupport{/***@description:将模板RedisTemplate<String,Object>中的key和value进行序列化*@param:RedisConnectionFactory*@return:RedisTemplate<String,Object>*@author:fastrabbit*@date:2021/6/119:12*/@BeanpublicRedisTemplate<String,Object>redisTemplate(RedisConnectionFactoryredisConnectionFactory){Jackson2JsonRedisSerializer<Object>serializer=newJackson2JsonRedisSerializer<Object>(Object.class);ObjectMapperobjectMapper=newObjectMapper();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=newRedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);redisTemplate.setKeySerializer(newStringRedisSerializer());redisTemplate.setValueSerializer(serializer);redisTemplate.setHashKeySerializer(newStringRedisSerializer());redisTemplate.setHashValueSerializer(serializer);redisTemplate.afterPropertiesSet();returnredisTemplate;}/***@description:设置RedisCacheManager*@param:RedisTemplate*@return:RedisCacheManager*@author:fastrabbit*@date:2021/6/119:12*/@BeanpublicRedisCacheManagerredisCacheManager(RedisTemplateredisTemplate){RedisCacheWriterredisCacheWriter=RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());RedisCacheConfigurationredisCacheConfiguration=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));returnnewRedisCacheManager(redisCacheWriter,redisCacheConfiguration);}}
14.redis的模板一些常用方法
packagecom.zengjx.project.redis.test;importio.swagger.models.auth.In;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.data.redis.connection.DataType;importorg.springframework.data.redis.core.*;importorg.springframework.test.context.junit4.SpringRunner;importjava.util.*;importjava.util.concurrent.TimeUnit;/***@authorfastrabbit*@date2021/6/99:30*/@RunWith(SpringRunner.class)@SpringBootTestpublicclassRedisTemplateTest{@AutowiredprivateRedisTemplate<String,Object>redisTemplate;@TestpublicvoidstringRedisTemplateTest(){//保存:保存key和valueredisTemplate.opsForValue().set("stringKey1","stringKey1_value");//保存:保存key和value如果Key存在则返回false否则保存成功并返回trueBooleanmessage1=redisTemplate.opsForValue().setIfAbsent("stringKey1","message1");System.out.println(message1);//保存:保存key和value并设置过期时间redisTemplate.opsForValue().set("stringKey2","stringKey2_value",20,TimeUnit.SECONDS);//保存:通过map的方式保存key和valueHashMap<String,Object>hashMap1=newHashMap<>();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=newHashMap<>();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否则报错:ERRnosuchkeyredisTemplate.opsForValue().set("stringKey6","stringKey6_value");Booleanmessage2=redisTemplate.renameIfAbsent("stringKey6","newStringKey6");System.out.println(message2);//修改:修改key的value值并返回原来的value值redisTemplate.opsForValue().set("stringKey7","stringKey7_value");Stringexchange=(String)redisTemplate.opsForValue().getAndSet("stringKey7","newStringKey7_value");System.out.println(exchange);//查询:获取指定key对应的value值redisTemplate.opsForValue().set("stringKey8","stringKey8_value");StringstringKey8=(String)redisTemplate.opsForValue().get("stringKey8");System.out.println(stringKey8);//查询:批量获取到key对应的value值参数为Collection<String>keysArrayList<String>arrayListKeys=newArrayList<>();arrayListKeys.add("stringKey1");arrayListKeys.add("stringKey2");arrayListKeys.add("stringKey3");List<Object>arrayListValues=redisTemplate.opsForValue().multiGet(arrayListKeys);for(ObjectarrayListValue:arrayListValues){System.out.println(arrayListValue);}//查询:获取指定Key的value值并设定截取长度redisTemplate.opsForValue().set("stringKey9","stringKey9_value");StringstringKey9Value=redisTemplate.opsForValue().get("stringKey9",1,5);System.out.println(stringKey9Value);//查询:获取指定key的过期时间redisTemplate.opsForValue().set("stringKey10","stringKey10_value",666,TimeUnit.SECONDS);LongstringKey10Expire=redisTemplate.getExpire("stringKey10",TimeUnit.SECONDS);System.out.println(stringKey10Expire);//查询:从redis中随机获取到一个key值StringrandomKey=redisTemplate.randomKey();System.out.println(randomKey);//查询:返回key的value的类型redisTemplate.opsForValue().set("stringKey11","stringKey11_value");DataTypestringKey11DataType=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和它的vlueredisTemplate.opsForValue().set("stringKey12","stringKey12_value");BooleandeleteStringKey12=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=newArrayList<>();arrayListDelete.add("stringKey13");arrayListDelete.add("stringKey14");arrayListDelete.add("stringKey15");LongdeleteArrayList=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");BooleanstringKey17Persist=redisTemplate.persist("stringKey17");System.out.println(stringKey17Persist);//其他:将当前库中的key移动到指定的库中redisTemplate.opsForValue().set("stringKey18","stringKey18_value");BooleanstringKey18Move=redisTemplate.move("stringKey18",1);System.out.println(stringKey18Move);//其他:获取到key的value字符串长度redisTemplate.opsForValue().set("stringKey19","stringKey19_value");LongstringKey19Size=redisTemplate.opsForValue().size("stringKey19");System.out.println(stringKey19Size);//其他:查看是否存在指定的keyBooleanhasStringKey19=redisTemplate.hasKey("stringKey19");System.out.println(hasStringKey19);}@TestpublicvoidhashRedisTemplateTest(){//保存:保存一个hashMapredisTemplate.opsForHash().put("hashKey1","field1","field1_value");//保存:保存一个hashMap仅当field不存在的时候才保存成功BooleanputIfAbsentField=redisTemplate.opsForHash().putIfAbsent("hashKey1","field1","field1_value_attach");System.out.println(putIfAbsentField);//保存:通过map的形式添加键值对HashMap<String,Object>hashMap3=newHashMap<>();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");StringgetSpecifyValue=(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(Objecto:getSpecifyMap.keySet()){System.out.println(o);System.out.println(getSpecifyMap.get(o));}//查询:获取指定hashkey中的所有field字段HashMap<String,Object>hashMap4=newHashMap<>();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(Objecto:getSpecifySet){System.out.println(o);}//查询:获取到指定hashKey的field的数量HashMap<String,Object>hashMap5=newHashMap<>();hashMap5.put("field7","fiele7_value");hashMap5.put("field7_attach1","fiele7_attach1_value");hashMap5.put("field7_attach2","fiele7_attach2_value");redisTemplate.opsForHash().putAll("hashKey7",hashMap5);LonghashKey7Size=redisTemplate.opsForHash().size("hashKey7");System.out.println(hashKey7Size);//查询:获取指定hashKey的所有field的value值HashMap<String,Object>hashMap6=newHashMap<>();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(ObjecthashKey8Value:hashKey8Values){System.out.println(hashKey8Value);}}@TestpublicvoidlistRedisTemplateTest(){//保存:存储在key链表的右边并返回长度LonglistKey1Length=redisTemplate.opsForList().rightPush("listKey1","listKey1_value");System.out.println(listKey1Length);//保存:存储多个值在list的右边参数为Collect<T>参数泛型需要和设置的模板的泛型一致,不然保存的是数组而不是数组元素redisTemplate.opsForList().rightPush("listKey2","listKey2_value");ArrayList<Object>arrayList1=newArrayList<>();arrayList1.add("listKey2_attach1_value");arrayList1.add("listKey2_attach2_value");arrayList1.add("listKey2_attach3_value");LonglistKey2Length1=redisTemplate.opsForList().rightPushAll("listKey2","listKey2_attach1_value","listKey2_attach2_value","listKey2_attach3_value");LonglistKey2Length2=redisTemplate.opsForList().rightPushAll("listKey2",arrayList1);System.out.println(listKey2Length1);System.out.println(listKey2Length2);//保存:存储在key连表的左边并返回长度LonglistKey3Length1=redisTemplate.opsForList().leftPush("listKey3","listKey3_value");LonglistKey3Length2=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=newArrayList<>();arrayList2.add("listKey4_attach1_value");arrayList2.add("listKey4_attach2_value");arrayList2.add("listKey4_attach3_value");LonglistKey4Length1=redisTemplate.opsForList().leftPushAll("listKey4","listKey4_attach1_value","listKey4_attach2_value","listKey4_attach3_value");LonglistKey4Length2=redisTemplate.opsForList().leftPushAll("listKey4",arrayList2);System.out.println(listKey4Length1);System.out.println(listKey4Length2);//保存:在指定的key中的pivot(key的value)的前面添加值如果存在则添加否则不添加并返回-1redisTemplate.opsForList().leftPush("listKey5","listKey5_value");LonglistKey5Length1=redisTemplate.opsForList().leftPush("listKey5","nothing","listKey5_attach1_value");System.out.println(listKey5Length1);//保存:在指定的key中的pivot(key的value)的后面添加值如果存在则添加否则不添加并返回-1redisTemplate.opsForList().rightPush("listKey6","listKey6_value");LonglistKey6Length1=redisTemplate.opsForList().rightPush("listKey6","nothing","listKey6_attach1_value");System.out.println(listKey6Length1);//保存:只有当链表存在的时候才加入否则返回0Longnothing1=redisTemplate.opsForList().leftPushIfPresent("nothing","test");Longnothing2=redisTemplate.opsForList().rightPushIfPresent("nothing","test");System.out.println(nothing1);System.out.println(nothing2);//修改:修改指定索引处的值如果索引大于链表长度或报错ERRindexoutofrangeredisTemplate.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");StringlistKey8IndexValues=(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(ObjectlistKey9RangeValue:listKey9RangeValues){System.out.println(listKey9RangeValue);}//删除:移除链表左边的第一个元素并获取到它的value值(如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止)可以设置超时时间redisTemplate.opsForList().rightPushAll("listKey10","listKey10_value","listKey10_attach1_value","listKey10_attach2_value");ObjectlistKey10PopValue=redisTemplate.opsForList().leftPop("listKey10",10,TimeUnit.SECONDS);System.out.println(listKey10PopValue);//删除:移除链表右边的第一个元素并获取到它的value值(如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止)可以设置超时时间redisTemplate.opsForList().rightPushAll("listKey11","listKey11_value","listKey11_attach1_value","listKey11_attach2_value");ObjectlistKey11PopValue=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");ObjectrightPopAndLeftPushValue=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");LonglistKey14Remove=redisTemplate.opsForList().remove("listKey14",0,"listKey14_value");LonglistKey15Remove=redisTemplate.opsForList().remove("listKey15",2,"listKey15_value");LonglistKey16Remove=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");LonglistKey17Size=redisTemplate.opsForList().size("listKey17");System.out.println(listKey17Size);}@TestpublicvoidsetRedisTemplateTest(){//保存:保存一个元素LongsetKey1Length1=redisTemplate.opsForSet().add("setKey1","setKey1_value");System.out.println(setKey1Length1);//保存:批量添加元素好像不能使用set、list集合来批量添加LongsetKey2Length1=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(ObjectsetKey3Value: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(ObjectsetKey4Value: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(Objecto:set5AndSet6intersect){System.out.println(o);}//查询:获取多个集合的交集ArrayList<String>arrayList1=newArrayList<>();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(Objecto:setKey7AndSet8AndSet9Intersect){System.out.println(o);}//查询:将一个集合和一个或者多个集合的交集存储到另一个集合中ArrayList<String>arrayList2=newArrayList<>();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=newArrayList<>();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(Objecto:setKey14AndSet15AndSet16Union){System.out.println(o);}//查询:获取一个和另一个或者一个和多个集合的并集并将集合存储在指定Key的reids中并返回集合长度LongsetKey14AndSet15AndSet16Length=redisTemplate.opsForSet().unionAndStore("setKey14",arrayList3,"setKey17");System.out.println(setKey14AndSet15AndSet16Length);//查询:获取一个和另一个或者一个和多个集合的差集就是第一个集合和其他集合独有的元素提取出来为一个新的集合ArrayList<String>arrayList4=newArrayList<>();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(Objecto:setKey18AndSet19AndSet20Difference){System.out.println(o);}//查询:获取一个和另一个或者一个和多个集合的差集并将集合设置到指定key的redis中并返回集合长度LongsetKey18AndSet19AndSet20Length=redisTemplate.opsForSet().differenceAndStore("setKey18",arrayList4,"setKey21");System.out.println(setKey18AndSet19AndSet20Length);//查询:随机获取一个集合中的元素redisTemplate.opsForSet().add("setKey22","setKey22_value","setKey22_attach1_value","setKey22_attach2_value");StringsetKey22RandomValues=(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(ObjectsetKey23Value:setKey23Values){System.out.println(setKey23Value);}//删除:移除指定Key中的value元素并返回集合长度redisTemplate.opsForSet().add("setKey24","setKey24_value","setKey24_attach1_value","setKey24_attach2_value");LongsetKey24Length=redisTemplate.opsForSet().remove("setKey24","setKey24_attach2_value");System.out.println(setKey24Length);//删除:随机删除指定key中的一个元素并返回redisTemplate.opsForSet().add("setKey25","setKey25_value","setKey25_attach1_value","setKey25_attach2_value");ObjectsetKey25Value=redisTemplate.opsForSet().pop("setKey25");System.out.println(setKey25Value);//其他:获取集合的大小redisTemplate.opsForSet().add("setKey26","setKey26_value","setKey26_attach1_value","setKey26_attach2_value");LongsetKey26Length=redisTemplate.opsForSet().size("setKey26");System.out.println(setKey26Length);}@TestpublicvoidzSetRedisTemplateTest(){//保存:保存一个一个元素到集合中第三个参数score为排序的权值权值越小排序越前(左)BooleanzSetKey1=redisTemplate.opsForZSet().add("zSetKey1","zSetKey1_value",1);System.out.println(zSetKey1);//修改:给指定的key的value的score增加值原来的score+新增值redisTemplate.opsForZSet().add("zSetKey2","zSetKey2_value",1);DoublezSetKey2Score=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);LongzSetKey3Rank=redisTemplate.opsForZSet().rank("zSetKey3","zSetKey3_attach2_value");System.out.println(zSetKey3Rank);//查询:获取集合集合给定区间的元素-1表示查询所有DefaultTypedTuple<Object>objectDefaultTypedTuple1=newDefaultTypedTuple<Object>("zSetKey4_value",1d);DefaultTypedTuple<Object>objectDefaultTypedTuple2=newDefaultTypedTuple<Object>("zSetKey4_attach1_value",2d);DefaultTypedTuple<Object>objectDefaultTypedTuple3=newDefaultTypedTuple<Object>("zSetKey4_attach2_value",3d);Set<ZSetOperations.TypedTuple<Object>>typedTuples=newHashSet<>();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){Doublescore=objectTypedTuple.getScore();Objectvalue=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){Doublescore=objectTypedTuple.getScore();Objectvalue=objectTypedTuple.getValue();System.out.println(score);System.out.println(value);}//查询key对应的value值在集合中的排名LongzSetKey4ValueRank=redisTemplate.opsForZSet().reverseRank("zSetKey4","zSetKey4_attach2_value");System.out.println(zSetKey4ValueRank);//获取集合的大小LongzSetKey4Length2=redisTemplate.opsForZSet().size("zSetKey4");System.out.println(zSetKey4Length2);//获取指定key和value中的score值Doublescore=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);LongzSetKey5Length1=redisTemplate.opsForZSet().remove("zSetKey5","zSetKey5_value");System.out.println(zSetKey5Length1);}@TestpublicvoidemptyRedis(){Set<String>keys=redisTemplate.keys("*");redisTemplate.delete(keys);}}
15.操作redis的一些注解的使用
packagecom.zengjx.project.annotation.service.impl;importcom.baomidou.mybatisplus.core.conditions.query.QueryWrapper;importcom.baomidou.mybatisplus.extension.plugins.pagination.Page;importcom.baomidou.mybatisplus.extension.service.impl.ServiceImpl;importcom.zengjx.project.common.Result;importcom.zengjx.project.annotation.entity.Food;importcom.zengjx.project.annotation.mapper.FoodMapper;importcom.zengjx.project.annotation.service.IFoodService;importcom.baomidou.mybatisplus.extension.service.impl.ServiceImpl;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.cache.annotation.CacheEvict;importorg.springframework.cache.annotation.CachePut;importorg.springframework.cache.annotation.Cacheable;importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Transactional;importjava.util.List;/***@authorfastrabbit*@date2021-06-11*/@Service@Transactional(rollbackFor=Exception.class)publicclassFoodServiceImplextendsServiceImpl<FoodMapper,Food>implementsIFoodService{@AutowiredprivateFoodMapperfoodMapper;@AutowiredprivateIFoodServicefoodService;/***@authorfastrabbit*@description根据id查询单个数据将查询到的数据放入到redis缓存中,如果根据key值能够在redis中找到则直接返回redis中的数据不执行代码condition为缓存条件*@date2021-06-11*/@Override@Cacheable(value="PROJECT:ANNOTATION",key="'FOOD:'+#food.id",condition="#food.id>0")publicResult<Food>getById(Foodfood){Result<Food>foodResult=newResult<>();foodResult.setData(foodMapper.selectById(food.getId()));returnfoodResult;}/***@authorfastrabbit*@description根据查询条件查询分页数据将查询到的数据放入到redis缓存中,如果根据key值能够在redis中找到则直接返回redis中的数据不执行代码condition为缓存条件*@date2021-06-11*/@Override@Cacheable(value="PROJECT:ANNOTATION",key="'FOOD:'+#food.page+'_'+#food.rows",condition="#food.page>0and#food.rows>=10")publicResult<List<Food>>findListByPage(Foodfood){Result<List<Food>>listResult=newResult<>();Page<Food>foodPage=newPage<>(food.getPage(),food.getRows());QueryWrapper<Food>foodQueryWrapper=newQueryWrapper<>();List<Food>records=foodMapper.selectPage(foodPage,foodQueryWrapper).getRecords();listResult.setData(records);listResult.setTotal(records.size());returnlistResult;}/***@authorfastrabbit*@description查询所有数据将查询到的数据放入到redis缓存中,如果根据key值能够在redis中找到则直接返回redis中的数据不执行代码*@date2021-06-11*/@Override@Cacheable(value="PROJECT:ANNOTATION",key="'FOOD:'+'ALL'")publicResult<List<Food>>getAll(){Result<List<Food>>foodResult=newResult<>();List<Food>foods=foodMapper.selectList(null);foodResult.setData(foods);foodResult.setTotal(foods.size());returnfoodResult;}/***@authorfastrabbit*@description新增单个数据*@date2021-06-11*/@OverridepublicResult<Object>insert(Foodfood){Result<Object>objectResult=newResult<>();foodMapper.insert(food);//通过调用上面的getById方法将新增的数据添加到redis中//因为redis注解存储的方式使用的是spring的aop动态代理所以通过注入自己的方式来使用代理类中的方法foodService.getById(food);returnobjectResult;}/***@authorfastrabbit*@description修改单个数据*@date2021-06-11*/@OverridepublicResult<Object>update(Foodfood){Result<Object>objectResult=newResult<>();foodMapper.updateById(food);//通过调用下面的redisUpdate方法将存储在redis中的数据进行更新//因为redis注解存储的方式使用的是spring的aop动态代理所以通过注入自己的方式来使用代理类中的方法Result<Food>byId=foodService.redisUpdate(food);Fooddata=byId.getData();System.out.println(data);returnobjectResult;}/***@authorfastrabbit*@Description修改redis缓存中的数据@CachePut注解:一定会执行代码然后将返回数据存放在redis中,保证数据库和redis中的数据一致性*@Date13:382021/6/11*/@Override@CachePut(value="PROJECT:ANNOTATION",key="'FOOD:'+#food.id",condition="#food.id>0")publicResult<Food>redisUpdate(Foodfood){Result<Food>foodResult=newResult<>();foodResult.setData(foodMapper.selectById(food.getId()));returnfoodResult;}/***@authorfastrabbit*@description删除单个数据@CacheEvict:当执行到该方法时会根据key将redis中的数据进行删除,具有多项配置*@date2021-06-11*/@Override@CacheEvict(value="PROJECT:ANNOTATION",key="'FOOD:'+#food.id",condition="#food.id>0")publicResult<Object>delete(Foodfood){Result<Object>objectResult=newResult<>();foodMapper.deleteById(food.getId());returnobjectResult;}}
以上就是“springboot+mybatisplus+redis的demo怎么实现”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注恰卡编程网行业资讯频道。
推荐阅读
-
vue动态添加删除输入框(springboot vue怎么让数据库显示出来)
springbootvue怎么让数据库显示出来?一般情况下是前端调阅后端接口,来获取到数据库的数据,后端哪里会把数据库的数据整理...
-
php如何让Swoole/Pool进程池实现Redis持久连接
php如何让Swoole/Pool进程池实现Redis持久连接本篇...
-
php操作redis大全记录
php连接redis测试˂?php$redis=newRedis();$redis-˃conne...
-
PHP经典高级工程师面试题
1.PHP如何实现不用自带的cookie函数为客户端下发cookie。对于分布式系统,如何来保存session值...
-
PHP操作Redis数据库
-
php利用redis防止商品超发来限制抢购,简单又实用
-
php如何实现秒杀功能?php+redis模拟简单抢购场景,快来看看吧
-
PHP高级工程师面试题
-
Laravel结合Redis发送邮箱验证码
-
使用redis缓存实现多服务器PHP sessions共享