当前位置:网站首页>Redis official ORM framework is more elegant than redistemplate
Redis official ORM framework is more elegant than redistemplate
2022-07-07 22:28:00 【1024 questions】
RedisOM brief introduction
JDK 11 install
Use
summary
Before that SpringBoot In the project , I always use RedisTemplate To operate Redis Data in , This is also Spring The way of official support . contrast Spring Data Yes MongoDB and ES Support for , This kind of use Template The way is really not elegant enough ! The recent discovery Redis Officially launched Redis Exclusive ORM frame RedisOM
, Elegant enough to use , I recommend it to you !
SpringBoot Actual e-commerce projects mall(50k+star) Address :github.com/macrozheng/…
RedisOM yes Redis Officially launched ORM frame , It's right Spring Data Redis An extension of . because Redis At present, it supports native JSON Object storage , Before using RedisTemplate Store... Directly in a string JOSN The way of objects is obviously not elegant . adopt RedisOM We can not only operate in the form of objects Redis Data in , And it can realize the search function !
JDK 11 install Due to the present RedisOM Support only JDK 11
Above version , We have to install it before we use it .
First download JDK 11
, Download address :https://www.jb51.net/softs/638448.html
Download the compressed package version , After downloading, extract to the specified directory ;
And then in IDEA In the project configuration , The corresponding module will be JDK The dependent version is set to JDK 11
that will do .
Next, let's manage the storage in Redis Take the commodity information in as an example , Realize the product search function . Pay attention to the installation Redis The full version of RedisMod
, For details, please refer to RediSearch Use the tutorial .
First, in the pom.xml
Add RedisOM Related dependencies ;
<!--Redis OM Related dependencies --><dependency> <groupId>com.redis.om</groupId> <artifactId>redis-om-spring</artifactId> <version>0.3.0-SNAPSHOT</version></dependency>
because RedisOM At present, there is only snapshot version , You also need to add a snapshot warehouse ;
<repositories> <repository> <id>snapshots-repo</id> <url>https://s01.oss.sonatype.org/content/repositories/snapshots/</url> </repository></repositories>
Then in the configuration file application.yml
Add Redis Connection configuration ;
spring: redis: host: 192.168.3.105 # Redis Server address database: 0 # Redis Database index ( The default is 0) port: 6379 # Redis Server connection port password: # Redis Server connection password ( The default is empty. ) timeout: 3000ms # Connection timeout
Then add... On the startup class @EnableRedisDocumentRepositories
Annotations to enable RedisOM Document warehouse function , And configure the path where the document warehouse is located ;
@[email protected](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 , Use @Document
The annotation identifies it as a document object , Because our search information contains Chinese , We need to set the language to chinese
;
/** * Commodity entity class * Created by macro on 2021/10/12. */@[email protected](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;}
Introduce the functions of several annotations in the code ;
@Id
: Declaration of primary key ,RedisOM Will pass through Full class name :ID
Such a key to store data ;
@Indexed
: Declaration index , Usually used on non text types ;
@Searchable
: Declare the index that can be searched , Usually used on text types .
Next, create a document warehouse interface , Inherit RedisDocumentRepository
Interface ;
/** * Commodity management Repository * Created by macro on 2022/3/1. */public interface ProductRepository extends RedisDocumentRepository<Product, Long> {}
Create a test Controller, adopt Repository
Realize to Redis Creation of data in 、 Delete 、 Query and paging function ;
/** * Use Redis OM Manage goods * Created by macro on 2022/3/1. */@[email protected](tags = "ProductController", description = " Use Redis OM Manage goods ")@RequestMapping("/product")public class ProductController { @Autowired private ProductRepository productRepository; @ApiOperation(" Import goods ") @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(" Create merchandise ") @PostMapping("/create") public CommonResult create(@RequestBody Product entity) { productRepository.save(entity); return CommonResult.success(null); } @ApiOperation(" Delete ") @PostMapping("/delete/{id}") public CommonResult delete(@PathVariable Long id) { productRepository.deleteById(id); return CommonResult.success(null); } @ApiOperation(" Query individual ") @GetMapping("/detail/{id}") public CommonResult<Product> detail(@PathVariable Long id) { Optional<Product> result = productRepository.findById(id); return CommonResult.success(result.orElse(null)); } @ApiOperation(" Paging query ") @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 , You can find RedisOM The document will be automatically indexed ;
Next we visit Swagger To test , First use Import goods
Interface import data , Access address :http://localhost:8088/swagger-ui/
After importing successfully, we can find RedisOM Already directed Redis Inserted native JSON data , In full class name :ID The form named the key , At the same time, all ID Stored in a SET In the collection ;
We can go through ID To query product information ;
Of course RedisOM It also supports derived queries , The query logic can be realized automatically through the method name we created , For example, query the goods according to the brand name , Search for products by name and subtitle keywords ;
/** * Commodity management Repository * Created by macro on 2022/3/1. */public interface ProductRepository extends RedisDocumentRepository<Product, Long> { /** * Query according to brand name */ List<Product> findByBrandName(String brandName); /** * Search by name or subtitle */ List<Product> findByNameOrSubTitle(String name, String subTitle);}
stay Controller The following interfaces can be added to test ;
/** * Use Redis OM Manage goods * Created by macro on 2022/3/1. */@[email protected](tags = "ProductController", description = " Use Redis OM Manage goods ")@RequestMapping("/product")public class ProductController { @Autowired private ProductRepository productRepository; @ApiOperation(" Inquire according to the brand ") @GetMapping("/getByBrandName") public CommonResult<List<Product>> getByBrandName(String brandName) { List<Product> resultList = productRepository.findByBrandName(brandName); return CommonResult.success(resultList); } @ApiOperation(" Search by name or subtitle ") @GetMapping("/search") public CommonResult<List<Product>> search(String keyword) { List<Product> resultList = productRepository.findByNameOrSubTitle(keyword, keyword); return CommonResult.success(resultList); }}
We can check the goods by brand name ;
You can also search for products through keywords ;
What are the rules for this kind of derivative query that automatically implements the query logic according to the method name , Refer to the following table for details .
Today I experienced a RedisOM, It's really elegant to use , And use Spring Data To operate MongoDB and ES In a similar way . But so far RedisOM Only the snapshot version has been released , expect Release Release of version , and Release The version is said to support JDK 8
Of !
If you want to know more Redis If you have practical skills , You can try this practical project with a full set of tutorials (50K+Star):github.com/macrozheng/…
Reference material
Project address :github.com/redis/redis…
Official documents :developer.redis.com/develop/jav…
Project source address github.com/macrozheng/…
That's all Redis official ORM Frame ratio RedisTemplate More elegant details , More about Redis official ORM For information about the framework, please pay attention to other relevant articles on the software development network !
边栏推荐
- Tcp/ip protocol stack
- [开源] .Net ORM 访问 Firebird 数据库
- How to choose the appropriate automated testing tools?
- JS number is insufficient, and 0 is added
- Revit secondary development - shielding warning prompt window
- 应用实践 | 数仓体系效率全面提升!同程数科基于 Apache Doris 的数据仓库建设
- It's worth seeing. Interview sites and interview skills
- Kirin Xin'an operating system derivative solution | storage multipath management system, effectively improving the reliability of data transmission
- Welcome to CSDN markdown editor
- How to make agile digital transformation strategy for manufacturing enterprises
猜你喜欢
[azure microservice service fabric] the service fabric cluster hangs up because the certificate expires (the upgrade cannot be completed, and the node is unavailable)
Display optimization when the resolution of easycvr configuration center video recording plan page is adjusted
100million single men and women "online dating", supporting 13billion IPOs
客户案例|华律网,通过观测云大幅缩短故障定位时间
Jerry's test box configuration channel [chapter]
Cannot find module 'xxx' or its corresponding type declaration
Ternary expressions, generative expressions, anonymous functions
vite Unrestricted file system access to
【Azure微服务 Service Fabric 】因证书过期导致Service Fabric集群挂掉(升级无法完成,节点不可用)
Preparing for the interview and sharing experience
随机推荐
Build your own website (18)
Record problems fgui tween animation will be inexplicably killed
Aspose. Words merge cells
It's worth seeing. Interview sites and interview skills
100million single men and women "online dating", supporting 13billion IPOs
Dayu200 experience officer MPPT photovoltaic power generation project dayu200, hi3861, Huawei cloud iotda
Failed to initialize rosdep after installing ROS
ByteDance senior engineer interview, easy to get started, fluent
Revit secondary development - collision detection
OpenGL job coordinate system
Attitude estimation (complementary filtering)
客户案例|华律网,通过观测云大幅缩短故障定位时间
C # Development -- pit encountered in JS intermodulation
[open source] Net ORM accessing Firebird database
Reinforcement learning - learning notes 9 | multi step TD target
Use blocconsumer to build responsive components and monitor status at the same time
How does win11 time display the day of the week? How does win11 display the day of the week today?
Remember an experience of using selectmany
Interview question 01.02 Determine whether it is character rearrangement - auxiliary array algorithm
新版代挂网站PHP源码+去除授权/支持燃鹅代抽