之前在SpringBoot我的项目中,我始终应用RedisTemplate来操作Redis中的数据,这也是Spring官网反对的形式。比照Spring Data对MongoDB和ES的反对,这种应用Template的形式的确不够优雅!最近发现Redis官网新推出了Redis的专属ORM框架RedisOM,用起来够优雅,举荐给大家!

SpringBoot实战电商我的项目mall(50k+star)地址:https://github.com/macrozheng/mall

RedisOM简介

RedisOM是Redis官网推出的ORM框架,是对Spring Data Redis的扩大。因为Redis目前曾经反对原生JSON对象的存储,之前应用RedisTemplate间接用字符串来存储JOSN对象的形式显著不够优雅。通过RedisOM咱们不仅可能以对象的模式来操作Redis中的数据,而且能够实现搜寻性能!

JDK 11装置

因为目前RedisOM仅反对JDK 11以上版本,咱们在应用前得先装置好它。
  • 首先下载JDK 11,这里举荐去清华大学开源软件镜像站下载,下载地址:https://mirrors.tuna.tsinghua...

  • 下载压缩包版本即可,下载实现后解压到指定目录;

  • 而后在IDEA的我的项目配置中,将对应模块的JDK依赖版本设置为JDK 11即可。

应用

接下来咱们以治理存储在Redis中的商品信息为例,实现商品搜寻性能。留神装置Redis的齐全体版本RedisMod,具体能够参考RediSearch 应用教程 。
  • 首先在pom.xml中增加RedisOM相干依赖;
<!--Redis OM 相干依赖--><dependency>    <groupId>com.redis.om</groupId>    <artifactId>redis-om-spring</artifactId>    <version>0.3.0-SNAPSHOT</version></dependency>
  • 因为RedisOM目前只有快照版本,还需增加快照仓库;
<repositories>    <repository>        <id>snapshots-repo</id>        <url>https://s01.oss.sonatype.org/content/repositories/snapshots/</url>    </repository></repositories>
  • 而后在配置文件application.yml中增加Redis连贯配置;
spring:  redis:    host: 192.168.3.105 # Redis服务器地址    database: 0 # Redis数据库索引(默认为0)    port: 6379 # Redis服务器连贯端口    password: # Redis服务器连贯明码(默认为空)    timeout: 3000ms # 连贯超时工夫
  • 之后在启动类上增加@EnableRedisDocumentRepositories注解启用RedisOM的文档仓库性能,并配置好文档仓库所在门路;
@SpringBootApplication@EnableRedisDocumentRepositories(basePackages = "com.macro.mall.tiny.*")public class MallTinyApplication {    public static void main(String[] args) {        SpringApplication.run(MallTinyApplication.class, args);    }}
  • 而后创立商品的文档对象,应用@Document注解标识其为文档对象,因为咱们的搜寻信息中蕴含中文,咱们须要设置语言为chinese
/** * 商品实体类 * Created by macro on 2021/10/12. */@Data@EqualsAndHashCode(callSuper = false)@Document(language = "chinese")public class Product {    @Id    private Long id;    @Indexed    private String productSn;    @Searchable    private String name;    @Searchable    private String subTitle;    @Indexed    private String brandName;    @Indexed    private Integer price;    @Indexed    private Integer count;}
  • 别离介绍下代码中几个注解的作用;

    • @Id:申明主键,RedisOM将会通过全类名:ID这样的键来存储数据;
    • @Indexed:申明索引,通常用在非文本类型上;
    • @Searchable:申明能够搜寻的索引,通常用在文本类型上。
  • 接下来创立一个文档仓库接口,继承RedisDocumentRepository接口;
/** * 商品治理Repository * Created by macro on 2022/3/1. */public interface ProductRepository extends RedisDocumentRepository<Product, Long> {}
  • 创立测试用的Controller,通过Repository实现对Redis中数据的创立、删除、查问及分页性能;
/** * 应用Redis OM治理商品 * Created by macro on 2022/3/1. */@RestController@Api(tags = "ProductController", description = "应用Redis OM治理商品")@RequestMapping("/product")public class ProductController {    @Autowired    private ProductRepository productRepository;    @ApiOperation("导入商品")    @PostMapping("/import")    public CommonResult importList() {        productRepository.deleteAll();        List<Product> productList = LocalJsonUtil.getListFromJson("json/products.json", Product.class);        for (Product product : productList) {            productRepository.save(product);        }        return CommonResult.success(null);    }    @ApiOperation("创立商品")    @PostMapping("/create")    public CommonResult create(@RequestBody Product entity) {        productRepository.save(entity);        return CommonResult.success(null);    }    @ApiOperation("删除")    @PostMapping("/delete/{id}")    public CommonResult delete(@PathVariable Long id) {        productRepository.deleteById(id);        return CommonResult.success(null);    }    @ApiOperation("查问单个")    @GetMapping("/detail/{id}")    public CommonResult<Product> detail(@PathVariable Long id) {        Optional<Product> result = productRepository.findById(id);        return CommonResult.success(result.orElse(null));    }    @ApiOperation("分页查问")    @GetMapping("/page")    public CommonResult<List<Product>> page(@RequestParam(defaultValue = "1") Integer pageNum,                                            @RequestParam(defaultValue = "5") Integer pageSize) {        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);        Page<Product> pageResult = productRepository.findAll(pageable);        return CommonResult.success(pageResult.getContent());    }}
  • 当咱们启动我的项目时,能够发现RedisOM会主动为文档建设索引;

  • 接下来咱们拜访Swagger进行测试,先应用导入商品接口导入数据,拜访地址:http://localhost:8088/swagger...

  • 导入胜利后咱们能够发现RedisOM曾经向Redis中插入了原生JSON数据,以全类名:ID的模式命名了键,同时将全副的ID存储到了一个SET汇合中去了;

  • 咱们能够通过ID来查问商品信息;

  • 当然RedisOM也是反对衍生查问的,通过咱们创立的办法名称就能够主动实现查问逻辑,比方依据品牌名称查问商品,依据名称和副标题关键字来搜寻商品;
/** * 商品治理Repository * Created by macro on 2022/3/1. */public interface ProductRepository extends RedisDocumentRepository<Product, Long> {    /**     * 依据品牌名称查问     */    List<Product> findByBrandName(String brandName);    /**     * 依据名称或副标题搜寻     */    List<Product> findByNameOrSubTitle(String name, String subTitle);}
  • 在Controller中能够增加如下接口进行测试;
/** * 应用Redis OM治理商品 * Created by macro on 2022/3/1. */@RestController@Api(tags = "ProductController", description = "应用Redis OM治理商品")@RequestMapping("/product")public class ProductController {    @Autowired    private ProductRepository productRepository;    @ApiOperation("依据品牌查问")    @GetMapping("/getByBrandName")    public CommonResult<List<Product>> getByBrandName(String brandName) {        List<Product> resultList = productRepository.findByBrandName(brandName);        return CommonResult.success(resultList);    }    @ApiOperation("依据名称或副标题搜寻")    @GetMapping("/search")    public CommonResult<List<Product>> search(String keyword) {        List<Product> resultList = productRepository.findByNameOrSubTitle(keyword, keyword);        return CommonResult.success(resultList);    }}
  • 咱们能够通过品牌名称来查问商品;

  • 也能够通过关键字来搜寻商品;

  • 这类依据办法名称主动实现查问逻辑的衍生查问有什么规定呢,具体能够参考下表。

总结

明天体验了一把RedisOM,用起来的确够优雅,和应用Spring Data来操作MongoDB和ES的形式差不多。不过目前RedisOM只公布了快照版本,期待Release版本的公布,而且Release版本据说会反对JDK 8的!

如果你想理解更多Redis实战技巧的话,能够试试这个带全套教程的实战我的项目(50K+Star):https://github.com/macrozheng/mall

参考资料

  • 我的项目地址:https://github.com/redis/redi...
  • 官网文档:https://developer.redis.com/d...

我的项目源码地址

https://github.com/macrozheng...