当前位置:网站首页>.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 F
9、 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);
边栏推荐
- 结构体操作报错:Segmentation fault (core dumped)
- 【C#语言】LINQ概述
- STM32 阿里云MQTT esp8266 AT命令
- Modelsim installation tutorial (application not installed)
- 【Halcon视觉】数组
- mysql 进不去了怎么办
- Centos8 (liunx) deploying WTM (asp.net 5) using PgSQL
- 【Halcon视觉】图像的傅里叶变换
- Draco developed by Google and Pixar supports USD format to accelerate 3D object transmission & lt; Forward & gt;
- vscode上使用anaconda(已经配置好环境)
猜你喜欢
QRcode二维码(C语言)遇到的问题
[leetcode每日一题2021/2/18]【详解】995. K 连续位的最小翻转次数
Introduction to data analysis | kaggle Titanic mission (I) - > data loading and preliminary observation
码云,正式支持 Pages 功能,可以部署静态页面
Centos8 (liunx) deploying WTM (asp.net 5) using PgSQL
The software cannot be opened
js 获得当前时间,时间与时间戳的转换
hx711 数据波动大的问题
单元测试,到底什么是单元测试,为什么单测这么难写
Cause: could't make a guess for solution
随机推荐
Wechat official account release reminder (wechat official account template message interface)
Tradingview 使用教程
抓包工具fiddler和wireshark对比
js下载文件,FileSaver.js导出txt、excel文件
Use of Android grendao database
Summary of common skills in H5 development of mobile terminal
Function templates and non template functions with the same name cannot be overloaded (definition of overloads)
Tradingview tutorial
10 令 operator= 返回一个 reference to *this
【Halcon视觉】数组
MLX90640 红外热成像仪测温传感器模块开发笔记(六)红外图像伪彩色编码
MD5加密
The CLOB field cannot be converted when querying Damon database
[Halcon vision] image filtering
12 复制对象时勿忘其每一个成分
MLX90640 红外热成像仪测温传感器模块开发笔记(六)
头歌 Phoenix 入门(第1关:Phoenix 安装、第2关:Phoenix 基础语法)
[leetcode每日一题2021/4/29]403. 青蛙过河
Introduction to data analysis | kaggle Titanic mission (I) - > data loading and preliminary observation
Centos8 (liunx) deploying WTM (asp.net 5) using PgSQL