关于java:还在用-RedisTemplate试试-Redis-官方-ORM-框架吧用起来够优雅

4次阅读

共计 5190 个字符,预计需要花费 13 分钟才能阅读完成。

之前在 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…

正文完
 0