当前位置:网站首页>Redis OM . Net redis object mapping framework
Redis OM . Net redis object mapping framework
2022-06-26 16:49:00 【Masa technical team】
Redis OM
Redis OM yes Redis The official object mapping framework , namely :Object Mapping. Make it easier for developers 、 Convenient operation Redis data .Redis The stored data is abstracted as object mapping , Support object-based Redis Data persistence 、 Streaming query operation .
Currently only supported 4 Development languages :
- Redis OM for Spring
- Redis OM for .NET
- Redis OM for Node.js
- Redis OM for Python
Redis OM .NET
Redis OM .NET yes .Net Platform Redis OM, rely on StackExchange.Redis Realization . With the help of Redis OM .NET Can realize the way of object operation Redis data , Out of the key/value How to operate . Query supports most .Neter favorite LINQ.
Quick start
Install the corresponding package
dotnet add package Redis.OMRedis Environmental preparation
Use it directly Docker Mode of installation Redis Environmental Science .
docker run -p 6379:6379 redislabs/redismod:previewThe standard official image cannot support Redis OM, need Redis Modules Support ,Redis OM Core index creation 、 Query data dependency
RediSearchThis Module Realization . Rely on the Module Yes :RediSearch、RedisJSON. RedisJSON Dependency is not necessary , But there will be a lack of corresponding functions , Such as : Model nesting 、 Complex queries ( Only support key Inquire about )
Coding
Add abstract object definition
[Document]public class Customer{ [RedisIdField] public string Id { get; set; } [Indexed(Sortable = true, Aggregatable = true)] public string FirstName { get; set; } [Indexed(Sortable = true, Aggregatable = true)] public string LastName { get; set; } [Indexed] public string Email { get; set; } [Indexed(Sortable = true)] public int Age { get; set; }}Document、Indexed、Searchable Introduction to other characteristics , Introduces the reference Github -> document-attribute
Get the operation collection of abstract objects 、 Create index
var provider = new RedisConnectionProvider("redis://localhost:6377");var connection = provider.Connection;var customers = provider.RedisCollection<Customer>();connection.CreateIndex(typeof(Customer)); Query data 、 Aggregation operations need to be based on the index , So be sure to call connection.CreateIndex Create index , Corresponding RediSearch Of FT.CREATE command .
connection.CreateIndex(typeof(Customer)) An exception is thrown when the index is created repeatedly
Index already exists. Although it can passconnection.Execute("FT.INFO", $"customer-idx")Get index information , But the first time the index does not exist, it will throwUnknown Index name. So in actual use, you may need a try-catch encaseCreateIndexMethods to avoid exceptions .
insert data
var id = customers.Insert(new Customer { FirstName = "Steve", Email = "[email protected]", Age = 1 });var id2 = customers.Insert(new Customer { FirstName = "FirstName", LastName = "LastName", Email = "[email protected]" });id,id2 For inserting data key, Is not specified Document Of Prefixes and IdGenerationStrategy, The default is ULID The format is {DocumentName}:{Ulid}, Such as :`Cust
When inserting data, you should pay attention to , If the value of the field is not explicitly specified , Such as LastName Ambiguous assignment :
customers.Insert(new Customer { FirstName = "Steve", Email = "[email protected]", Age = 1 });, see Redis The data stored in can find the current key Stored json The data does not correspond to an unspecified field key( here Query or Aggregations There will be some strange mistakes ). According to their own needs , The displayed field is assigned a zero value or used when defining an entitypublic string LastName { get; set; } = string.Empty;The way .
Query data
var customer = customers.Where(x => x.Age == 0).OrderBy(a => a.FirstName).FirstOrDefault();var customerById = customers.FindById(id);// according to Id lookup var emails = customers.Select(x => x.Email);// Query only the specified fields var takes = customers.Where(x => x.Age > 0).Take(10);// Get the specified number var adults = customers.Where(x => x.Age >= 0).Skip(5);// Query offset Judgment of null value ,x.FirstName == ""【 Grammar mistakes 】 or string.IsNullOrEmpty(x.FirstName)【 I won't support it 】.Redis Cannot have empty string in hash , Therefore, similar queries should be operated through aggregation Exists Method realization
foreach (var agg in customerAggregations.Apply(x => ApplyFunctions.Exists(x.RecordShell.LastName), "LastNameExists")){ Console.WriteLine($"{agg["LastNameExists"]}");}Aggregation operation
Assembly line (Pipelining) Send multiple requests at the same time , So as to reduce the delay . The query and transformation of the results are Redis The complete .
RecordShell It's the far end Index The structure of the type ,RecordShell Should only be used inside the aggregation pipeline , There is no real value at runtime .
Put together FirstName and LastName, return FullName
var customerAggregations = provider.AggregationSet<Customer>();var age = customerAggregations.Average(x => x.RecordShell.Age);var sets = customerAggregations.Where(a => a.RecordShell.FirstName == "Steve").Apply(x => string.Format("{0} {1}", x.RecordShell.FirstName, x.RecordShell.LastName), "FullName");foreach (var item in sets){ Console.WriteLine(item["FullName"].ToString());}Group together
adopt GroupBy Method , Group and aggregate according to different attributes ( Support single field grouping and multi field grouping ).
var res = customerAggregations .GroupBy(x => x.RecordShell.FirstName) .GroupBy(x => x.RecordShell.LastName) .ToArray();var res1 = customerAggregations.GroupBy(x => x.RecordShell.FirstName).CloseGroup().ToArray();CloseGroup You can turn off grouping , Convert to normal aggregation operation , namely GroupedAggregationSet To RedisAggregationSet A transformation of .
public static RedisAggregationSet<T> CloseGroup<T>(this GroupedAggregationSet<T> source){ return new RedisAggregationSet<T>(source, source.Expression);}ending
This article is just for Redis OM .NET Simple sorting of usage and usability verification . More usage and usage update reference Github
We are acting , New framework 、 New ecology
Our goal is The freedom of the 、 Easy-to-use 、 Highly malleable 、 functional 、 Robust .
So we learn from Building blocks Design concept of , Working on a new framework MASA Framework, What are its characteristics ?
- Native support Dapr, And allow Dapr Replace with traditional means of communication
- Unlimited architecture , Single application 、SOA、 Micro services support
- Support .Net Native framework , Reduce the burden of learning , In addition to the concepts that must be introduced in a specific field , Insist on not making new wheels
- Rich ecological support , In addition to the framework, there are component libraries 、 Authority Center 、 Configuration center 、 Troubleshooting center 、 A series of products such as Alarm Center
- Unit test coverage of the core code base 90%+
- Open source 、 free 、 Community driven
- What is the ? We are waiting for you , Come together and discuss
After several months of production project practice , Completed POC, At present, the previous accumulation is being refactored into new open source projects
At present, the source code has been synchronized to Github( The document site is under planning , Will gradually improve ):
QQ Group :7424099
Wechat group : Plus technology operation wechat (MasaStackTechOps), Remarks , Invite in

------ END ------
Author's brief introduction
** Ma Yue :**MASA Technical team members .
边栏推荐
- Toupper function
- What is flush software? Is it safe to open an account online?
- Redis 概述整理
- pybullet机器人仿真环境搭建 5.机器人位姿可视化
- Qt 5.9.8 安装教程
- Some instance methods of mono
- 108. 简易聊天室11:实现客户端群聊
- [force deduction question] two point search: 4 Find the median of two positive arrays
- Dialogue with the senior management of Chang'an Mazda, new products will be released in Q4, and space and intelligence will lead the Japanese system
- 内存分区模型
猜你喜欢

C语言所有知识点小结

MS | Xie Liwei group found that mixed probiotics and their metabolites could alleviate colitis

内存分区模型

Teach you to learn dapr - 5 Status management

架构实战营毕业设计

Leetcode 1170. 比较字符串最小字母出现频次(可以,已解决)
![[graduation season] a word for graduates: the sky is high enough for birds to fly, and the sea is wide enough for fish to leap](/img/b6/21e51fa7f79d4a4b950f061703f0fb.png)
[graduation season] a word for graduates: the sky is high enough for birds to fly, and the sea is wide enough for fish to leap

数字藏品与NFT到底有何区别

Constructors and Destructors

Teach you to learn dapr - 4 Service invocation
随机推荐
Data analysis - numpy quick start
Cloud platform monitoring system based on stm32+ Huawei cloud IOT design
Stm32f103c8t6 realize breathing lamp code
Gui+sqlserver examination system
Failed to upload hyperf framework using alicloud OSS
proxy
并发编程整体脉络
proxy
Toupper function
108. simple chat room 11: realize client group chat
Redis 概述整理
基于Kubebuilder开发Operator(入门使用)
Overall context of concurrent programming
Some instance methods of mono
数字藏品与NFT到底有何区别
网页课程设计大作业——华山旅游网
What is the preferential account opening policy of securities companies now? Is it safe to open an account online now?
Codeforces Round #802 (Div. 2)
The function keeps the value of variable H to two decimal places and rounds the third digit
Make up the weakness - Open Source im project openim about initialization / login / friend interface document introduction