之前在SpringBoot项目中,我一直使用RedisTemplate来操作Redis中的数据,这也是Spring官方支持的方式。对比Spring Data对MongoDB和ES的支持,这种使用Template的方式确实不够优雅!最近发现Redis官方新推出了Redis的专属ORM框架
RedisOM
,用起来够优雅,推荐给大家!
RedisOM是Redis官方推出的ORM框架,是对Spring Data Redis的扩展。由于Redis目前已经支持原生JSON对象的存储,之前使用RedisTemplate直接用字符串来存储JOSN对象的方式明显不够优雅。通过RedisOM我们不仅能够以对象的形式来操作Redis中的数据,而且可以实现搜索功能!
由于目前RedisOM仅支持
JDK 11
以上版本,我们在使用前得先安装好它。
JDK 11
,这里推荐去清华大学开源软件镜像站
下载,下载地址:https://mirrors.tuna.tsinghua.edu.cn/AdoptOpenJDK/11/jdk/x64/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>
<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> {
}
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());
}
}
导入商品
接口导入数据,访问地址:http://localhost:8088/swagger-ui/全类名:ID
的形式命名了键,同时将全部的ID存储到了一个SET集合中去了;/**
* 商品管理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);
}
/**
* 使用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
的!
https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-redis-om