当前位置:网站首页>.net operation redis hash object
.net operation redis hash object
2022-07-26 10:34:00 【Miners learn programming】
One 、Hash Object overview
Hash is widely used in many programming languages , And in the Redis It's the same with China , stay redis in , Hash type refers to Redis The value in the key value pair itself is a key value pair structure , Form like value=[{field1,value1},...{fieldN,valueN}].
Redis Each of them hash Can be stored 232 - 1 Key value pair (40 More than ).
Two 、 Use scenarios
Redis Hash objects are often used to cache some object information , Such as user information 、 Commodity information 、 Configuration information, etc .
3、 ... and 、.NET operation
1、 Basic operation
string hashid = "kgxk";
client.SetEntryInHash(hashid, "id", "001");
Console.WriteLine(client.GetValuesFromHash(hashid, "id").FirstOrDefault());
Console.WriteLine(client.GetValuesFromHash(hashid, "name").FirstOrDefault());
client.SetEntryInHash(hashid, "socre", "100");
Console.WriteLine(client.GetValuesFromHash(hashid, "socre").FirstOrDefault());2、 Batch add key Value
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("id", "001");
pairs.Add("name", "kgxk");
client.SetRangeInHash(hashid, pairs);
// Get current key Value
Console.WriteLine(client.GetValueFromHash(hashid, "id"));
Console.WriteLine(client.GetValueFromHash(hashid, "name"));
// Get all the small things you want at one time key( Attribute ) value If key non-existent , It returns null , Don't throw exceptions
var list = client.GetValuesFromHash(hashid, "id", "name", "abc");
Console.WriteLine("*********");
foreach (var item in list)
{
Console.WriteLine(item);
}3、 If hashid Exists in collection key/value Return without adding false, If it doesn't exist, add key/value, return true
Console.WriteLine(client.SetEntryInHashIfNotExists(hashid, "name", " you're pretty "));
Console.WriteLine(client.SetEntryInHashIfNotExists(hashid, "name", " you're pretty Ha ha ha "));
Console.WriteLine(client.GetValuesFromHash(hashid, "name").FirstOrDefault());4、 Store the object T t To hash Collection
//urn: Class name : id Value 、、 If you use object operations , Be sure to have id
client.StoreAsHash<UserInfo>(new UserInfo() { Id = 1, Name = "KGXK", Number = 0 });
client.StoreAsHash<UserInfo>(new UserInfo() { Id = 2, Name = "SXY", Number = 1 });
var olduserinfo = client.GetFromHash<UserInfo>(2);
Console.WriteLine(olduserinfo.Id);// If id exist , Then overwrite the same id He helps us serialize or reflect something
client.StoreAsHash<UserInfo>(new UserInfo() { Id = 2, Name = "KGXK2" });
// Get objects T in ID by id The data of . There must be attributes id, Case insensitive
Console.WriteLine(client.GetFromHash<UserInfo>(1).Name);
var olduserinfo = client.GetFromHash<UserInfo>(1);
olduserinfo.Number = 4;
client.StoreAsHash<UserInfo>(olduserinfo);
Console.WriteLine(" The final result " + client.GetFromHash<UserInfo>(1).Number);UserInfo lisi = new UserInfo() { Id = 1, Name = " Li Si ", Number = 0 };
client.StoreAsHash<UserInfo>(lisi);
Console.WriteLine(client.GetFromHash<UserInfo>(1).Number);
// Make a self increase
var oldzhang = client.GetFromHash<UserInfo>(1);
oldzhang.Number++;
client.StoreAsHash<UserInfo>(oldzhang);5、 obtain hashid The total number of data in the dataset
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("id", "001");
pairs.Add("name", "kgxk");
client.SetRangeInHash(hashid, pairs);
// Get the total number of data
Console.WriteLine(client.GetHashCount(hashid));6、 obtain hashid All in the dataset key or value Set
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("id", "001");
pairs.Add("name", "kgxk");
client.SetRangeInHash(hashid, pairs);
var keys = client.GetHashKeys(hashid);//key
//var values = client.GetHashValues(hashid); //value
foreach (var item in keys)
{
Console.WriteLine(item);
}7、 Delete hashid In dataset key data
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("id", "001");
pairs.Add("name", "kgxk");
client.SetRangeInHash(hashid, pairs);
client.RemoveEntryFromHash(hashid, "id");
var values = client.GetHashValues(hashid);
foreach (var item in values)
{
Console.WriteLine(item);
}8、 Judge hashid Whether the data set exists key
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("id", "001");
pairs.Add("name", "kgxk");
client.SetRangeInHash(hashid, pairs);
Console.WriteLine(client.HashContainsEntry(hashid, "id")); //T F
Console.WriteLine(client.HashContainsEntry(hashid, "number"));// T F9、 to hashid Data sets key Of value Add countby, Return the added data
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("id", "001");
pairs.Add("name", "kgxk");
pairs.Add("number", "2");
client.SetRangeInHash(hashid, pairs);
Console.WriteLine(client.IncrementValueInHash(hashid, "number", 2));
// Be careful , The stored value must be of numeric type , Otherwise, throw an exception 10、 Generic encapsulation
public static class HashHelper
{
public static void StoreAsHash<T>(T model,RedisClient client) where T : class, new()
{
// Get all fields of the current type
Type type = model.GetType();
var fields = type.GetProperties();
// urn: Class name : id Value
var hashid = type.FullName;
Dictionary<string, string> pairs = new Dictionary<string, string>();
var IdValue = string.Empty;
for (int i = 0; i < fields.Length; i++)
{
if (fields[i].Name.ToLower() == "id")
{
// If you really put two of the same id The object of is saved , I may only change one of them
// impossible , If there are two identical id The object of is saved , Then the latter will replace the former
IdValue = fields[i].GetValue(model).ToString();
}
else
{
// Get the value of the field
pairs.Add(fields[i].Name, fields[i].GetValue(model).ToString());
}
}
if (IdValue == string.Empty)
{
IdValue = DateTime.Now.ToString("yyyyMMdd");
}
client.SetRangeInHash(hashid + IdValue, pairs);
}
public static T GetFromHash<T>(object id, RedisClient client) where T : class, new()
{
// Get all fields of the current type
Type type = typeof(T);
// urn: Class name : id Value
var hashid = type.FullName;
var dics = client.GetAllEntriesFromHash(hashid + id.ToString());
if (dics.Count == 0)
{
return new T();
}
else
{
var model = Activator.CreateInstance(type);
var fields = type.GetProperties();
foreach (var item in fields)
{
if (item.Name.ToLower() == "id")
{
item.SetValue(model, id);
}
if (dics.ContainsKey(item.Name))
{
item.SetValue(model, dics[item.Name]);
}
}
return (T)model;
}
}
}call
HashHelper.StoreAsHash<UserInfoTwo>(new UserInfoTwo() { Id = "10001", Name = "MMM" }, client);
var user = HashHelper.GetFromHash<UserInfoTwo>("10001", client);
Console.WriteLine(user.Name);
Console.WriteLine(user.Id);
边栏推荐
猜你喜欢
![[leetcode每日一题2021/8/30]528. 按权重随机选择【中等】](/img/13/c6cb176d7065035f60d55ad20ed1bf.png)
[leetcode每日一题2021/8/30]528. 按权重随机选择【中等】

Okaleido ecological core equity Oka, all in fusion mining mode

videojs转canvas暂停、播放、切换视频

【Halcon视觉】图像的傅里叶变换

【dectectron2】跟着官方demo一起做

Review of database -- 1. Overview
![Structure of [Halcon vision] operator](/img/d9/e16ea52cea7897e3a1d61d83de472f.png)
Structure of [Halcon vision] operator

【Halcon视觉】编程逻辑

Unit test, what is unit test and why is it so difficult to write a single test
![[leetcode每日一题2021/4/29]403. 青蛙过河](/img/fb/612777c77df5a611506e72f4f4c3c8.png)
[leetcode每日一题2021/4/29]403. 青蛙过河
随机推荐
记给esp8266烧录刷固件
.NET操作Redis Set无序集合
比较器(Comparable与Comparator接口)
Li Kou daily question 917
string null转空字符串(空字符串是什么意思)
[leetcode每日一题2021/2/14]765. 情侣牵手
videojs转canvas暂停、播放、切换视频
原生JS-获取transform值 x y z及rotate旋转角度
Inheritance method of simplified constructor (I) - combined inheritance
【dectectron2】跟着官方demo一起做
The CLOB field cannot be converted when querying Damon database
404页面和路由钩子
Draco developed by Google and Pixar supports USD format to accelerate 3D object transmission & lt; Forward & gt;
Centos8 (liunx) deploying WTM (asp.net 5) using PgSQL
事务的传播性propagation
MLX90640 红外热成像仪测温传感器模块开发笔记(六)红外图像伪彩色编码
Some web APIs you don't know
[Halcon vision] polar coordinate transformation
【Halcon视觉】图像滤波
移动端H5开发常用技巧总结