当前位置: 首页 > 后端技术 > Java

还在用RedisTemplate吗?试试Redis官方的ORM框架,够优雅好用!

时间:2023-04-01 21:42:36 Java

之前在SpringBoot项目中,一直使用RedisTemplate操作Redis中的数据,这也是Spring官方支持的方式。相对于SpringData对MongoDB和ES的支持,这种Template的使用方式确实不够优雅!最近发现Redis官方推出了Redis专属的ORM框架RedisOM,够优雅好用,推荐给大家!SpringBoot实战电商项目商城(50k+star)地址:https://github.com/macrozheng/mallRedisOM简介RedisOM是Redis官方推出的ORM框架,是对SpringDataRedis的扩展。由于Redis目前支持原生JSON对象的存储,之前使用RedisTemplate直接用字符串存储JSON对象的方式显然不够优雅。通过RedisOM,我们不仅可以以对象的形式对Redis中的数据进行操作,还可以实现查找功能!JDK11安装由于RedisOM只支持JDK11及以上版本,所以我们在使用前必须先安装。首先下载JDK11,建议去清华大学开源软件镜像站下载,下载地址:https://mirrors.tuna.tsinghua...下载压缩包版即可,解压到下载后指定目录;然后在IDEA项目配置中,设置对应模块的JDK依赖版本为JDK11。接下来我们以管理存储在Redis中的商品信息为例,实现商品搜索功能。注意安装RedisMod,完整版的Redis。具体请参考RediSearch教程。首先在pom.xml中添加RedisOM相关的依赖;com.redis.omredis-om-spring0.3.0-SNAPSHOT由于RedisOM目前只有快照版本,需要添加快照仓库;snapshots-repohttps://s01.oss.sonatype.org/content/repositories/snapshots/然后在配置文件application.yml中添加Redis连接配置;spring:redis:host:192.168.3.105#Redis服务器地址database:0#Redis数据库索引(默认为0)port:6379#Redis服务器连接端口密码:#Redis服务器连接密码(默认为空)timeout:3000ms#添加@EnableRedisDocumentRepositories给连接超时后的启动类注解开启RedisOM的文档仓库功能,并配置文档仓库的路径;@SpringBootApplication@EnableRedisDocumentRepositories(basePackages="com.macro.mall.tiny.*")publicclassMallTinyApplication{publicstaticvoidmain(String[]args){SpringApplication.run(MallTinyApplication.class,args);}}然后创建商品的文档对象,并使用@Document注解将其标记为文档对象。由于我们的搜索信息包含中文,所以需要将语言设置为中文;/***产品实体类*宏创建于2021/10/12。*/@Data@EqualsAndHashCode(callSuper=false)@Document(language="chinese")publicclassProduct{@IdprivateLongid;@Indexed私有字符串productSn;@Searchable私有字符串名称;@SearchableprivateString副标题;@Indexed私有字符串品牌名称;@Indexed私有整数价格;@IndexedprivateIntegercount;}分别介绍代码中几个注解的作用;@Id:声明主键,RedisOM将数据按全类名:ID等键存储;@Indexed:声明索引,通常用在非文本类型上;@Searchable:声明可搜索索引,通常用在文本类型上接下来创建文档仓库接口,继承RedisDocumentRepository接口;/***产品管理存储库*由宏创建于2022/3/1。*/publicinterfaceProductRepositoryextendsRedisDocumentRepository{}创建一个Controller用于测试,通过Repository在Redis中创建、删除、查询和分页数据;/***使用RedisOM管理产品*宏创建于2022/3/1。*/@RestController@Api(tags="ProductController",description="使用RedisOM管理产品")@RequestMapping("/product")publicclassProductController{@AutowiredprivateProductRepositoryproductRepository;@ApiOperation("ImportProducts")@PostMapping("/import")publicCommonResultimportList(){productRepository.deleteAll();ListproductList=LocalJsonUtil.getListFromJson("json/products.json",Product.class);for(Productproduct:productList){productRepository.save(product);}返回CommonResult.success(null);}@ApiOperation("创建商品")@PostMapping("/create")publicCommonResultcreate(@RequestBodyProductentity){productRepository.save(entity);returnCommonResult.success(null);}@ApiOperation("删除")@PostMapping("/delete/{id}")publicCommonResultdelete(@PathVariableLongid){productRepository.deleteById(id);returnCommonResult.success(null);}@ApiOperation("查询单个")@GetMapping("/detail/{id}")publicCommonResultdetail(@PathVariableLongid){Optionalresult=productRepository.findById(id);returnCommonResult.success(result.orElse(null));}@ApiOperation("页面查询")@GetMapping("/page")publicCommonResult>page(@RequestParam(defaultValue="1")IntegerpageNum,@RequestParam(defaultValue="5")IntegerpageSize){Pageablepageable=PageRequest.of(pageNum-1,pageSize);PagepageResult=productRepository.findAll(pageable);returnCommonResult.success(pageResult.getContent());}}当我们启动项目时,可以发现RedisOM会自动索引文档;然后我们访问Swagger进行测试,首先使用导入商品接口导入数据,访问地址:http://localhost:8088/swagger...之后import成功,我们可以发现RedisOM已经往Redis中插入了原生的JSON数据,以全类名的形式给key命名:ID,并将所有的ID存储在一个SET集合中;我们可以通过ID查询产品信息;当然是RedisOM同样对于支持派生查询的,可以通过我们创建的方法名自动实现查询逻辑,比如通过品牌名称查询商品,通过名称和副标题关键词搜索商品;/***ProductManagementRepository*Createdbymacroon2022/3/1.*/publicinterfaceProductRepositoryextendsRedisDocumentRepository{/***按品牌名称搜索*/ListfindByBrandName(StringbrandName);/***按名称或副标题搜索*/ListfindByNameOrSubTitle(Stringname,StringsubTitle);}可以在Controller中添加如下接口进行测试;/***使用RedisOM管理产品*宏创建于2022/3/1。*/@RestController@Api(tags="产品ctController",description="使用RedisOM管理商品")@RequestMapping("/product")publicclassProductController{@AutowiredprivateProductRepositoryproductRepository;@ApiOperation("按品牌查询")@GetMapping("/getByBrandName")publicCommonResult>getByBrandName(StringbrandName){ListresultList=productRepository.findByBrandName(brandName);returnCommonResult.success(resultList);}@ApiOperation("按名称或副标题搜索")@GetMapping("/search")publicCommonResult>search(Stringkeyword){ListresultList=productRepository.findByNameOrSubTitle(keyword,keyword);returnCommonResult.success(resultList);}}我们可以通过品牌名称查询产品;也可以通过关键词搜索商品;这种根据方法名自动实现查询逻辑的派生查询有什么规则呢,具体可以参考下表总结一下,今天体验了一个RedisOM,这确实足够优雅,可以使用。MongoDB和ES的操作方式类似。不过RedisOM目前只发布了快照版本,期待Release版本的发布,据说Release版本支持JDK8!如果想深入了解Redis实战技巧,可以试试这个实战项目,全套教程(50K+Star):https://github.com/macrozheng/mall参考项目地址:https://github。com/redis/redi...官方文档:https://developer.redis.com/d...项目源码地址https://github.com/macrozheng...