In the SpringBoot project before, I have been using RedisTemplate to manipulate the data in Redis, which is also officially supported by Spring. Compared with Spring Data's support for MongoDB and ES, this way of using Template is really not elegant! Recently, I found that Redis officially launched a new exclusive ORM framework for Redis, RedisOM
, which is elegant enough to use. I recommend it to everyone!
SpringBoot actual e-commerce project mall (50k+star) address: https://github.com/macrozheng/mall
Introduction to RedisOM
RedisOM is an ORM framework officially launched by Redis, which is an extension to Spring Data Redis. Since Redis currently supports the storage of native JSON objects, the previous method of using RedisTemplate to store JSON objects directly with strings is obviously not elegant. Through RedisOM, we can not only manipulate the data in Redis in the form of objects, but also realize the search function!
JDK 11 installation
Since RedisOM currently only supports versions above JDK 11
, we must install it before using it.
- First download
JDK 11
, here it is recommended to go toTsinghua University open source software mirror site to download, download address: https://mirrors.tuna.tsinghua.edu.cn/AdoptOpenJDK/11/jdk/x64/
- Download the compressed package version, and extract it to the specified directory after the download is complete;
- Then in IDEA's project configuration, set the JDK dependency version of the corresponding module to
JDK 11
.
use
Next, we take managing the product information stored in Redis as an example to implement the product search function. Pay attention to install the full version of Redis RedisMod
. For details, please refer to RediSearch usage tutorial .
- First add RedisOM related dependencies in
pom.xml
;
<!--Redis OM 相关依赖-->
<dependency>
<groupId>com.redis.om</groupId>
<artifactId>redis-om-spring</artifactId>
<version>0.3.0-SNAPSHOT</version>
</dependency>
- Since RedisOM currently only has a snapshot version, a snapshot repository needs to be added;
<repositories>
<repository>
<id>snapshots-repo</id>
<url>https://s01.oss.sonatype.org/content/repositories/snapshots/</url>
</repository>
</repositories>
- Then add the Redis connection configuration in the configuration file
application.yml
;
spring:
redis:
host: 192.168.3.105 # Redis服务器地址
database: 0 # Redis数据库索引(默认为0)
port: 6379 # Redis服务器连接端口
password: # Redis服务器连接密码(默认为空)
timeout: 3000ms # 连接超时时间
- Then add the
@EnableRedisDocumentRepositories
annotation to the startup class to enable the document warehouse function of RedisOM, and configure the path where the document warehouse is located;
@SpringBootApplication
@EnableRedisDocumentRepositories(basePackages = "com.macro.mall.tiny.*")
public class MallTinyApplication {
public static void main(String[] args) {
SpringApplication.run(MallTinyApplication.class, args);
}
}
- Then create the document object of the product and use the
@Document
annotation to identify it as a document object. Since our search information contains Chinese, we need to set the language tochinese
;
/**
* 商品实体类
* 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;
}
The functions of several annotations in the code are introduced respectively;
@Id
: Declare the primary key, RedisOM will store data through keys such asfull class name: ID;
@Indexed
: declare index, usually used on non-text types;@Searchable
: Declare a searchable index, usually used on text types.
- Next, create a document warehouse interface, inheriting the
RedisDocumentRepository
interface;
/**
* 商品管理Repository
* Created by macro on 2022/3/1.
*/
public interface ProductRepository extends RedisDocumentRepository<Product, Long> {
}
- Create a controller for testing, and implement the functions of creating, deleting, querying and paging data in Redis through
Repository
;
/**
* 使用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());
}
}
- When we start the project, we can find that RedisOM will automatically index documents;
- Next, we visit Swagger for testing, first use
to import product interface to import data, access address: http://localhost:8088/swagger-ui/
- After the import is successful, we can find that RedisOM has inserted native JSON data into Redis, named keys in the form of
full class name: ID, and stored all IDs in a SET collection;
- We can query product information by ID;
- Of course, RedisOM also supports derivative queries, and the query logic can be automatically implemented through the method name we created, such as querying products by brand name, and searching for products by name and subtitle keywords;
/**
* 商品管理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);
}
- The following interfaces can be added to the Controller for testing;
/**
* 使用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);
}
}
- We can search for products by brand name;
- You can also search for products by keywords;
- What are the rules for this type of derivative query that automatically implements query logic based on method names? For details, please refer to the following table.
Summarize
I experienced a RedisOM today, and it is really elegant to use, which is similar to using Spring Data to operate MongoDB and ES. However, at present RedisOM only released the snapshot version, looking forward to the release of the Release version, and the Release version is said to support JDK 8
!
If you want to learn more Redis combat skills, you can try this practical project with a full set of tutorials (50K+Star): https://github.com/macrozheng/mall
References
- Project address: https://github.com/redis/redis-om-spring
- Official documentation: https://developer.redis.com/develop/java/spring/redis-om/redis-om-spring-json
Project source code address
https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-redis-om
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。