当前位置:网站首页>csredis-in-asp. Net core theory practice - use examples
csredis-in-asp. Net core theory practice - use examples
2022-06-12 22:38:00 【Wind god Shura envoy】
Premise
- Install and configure redis service , You can use .
- vs2017 or vs2019 or vscode
- .net core 2.2+ sdk
Create a . NET Core WebAPI project
Want to execute . NET Core CLI Command line , want cd To csproj In the same level directory
dotnet add package CSRedisCore
#mvc Distributed cache injection
dotnet add package Caching.CSRedis
or
Package management console (Package Manager) Run in , Choose your project
Install-Package CSRedisCore
Install-Package Caching.CSRedis
Common mode
appsettings.jsonConfiguration item
{
"CsRedisConfig": {
"DefaultConnectString": "127.0.0.1:6379,password=,defaultDatabase=0,prefix=csredis-default-"
}
}
Startup.csThe configuration in is as follows
public void ConfigureServices(IServiceCollection services)
{
// eg 1. Single redis Realization Common mode
//CSRedisClient csredis = new CSRedisClient("127.0.0.1:6379,password=,defaultDatabase=csredis,prefix=csredis-example");
//eg 2. Single redis, Use appsettings.json Configuration items in
IConfigurationSection configurationSection = Configuration.GetSection("CsRedisConfig:DefaultConnectString");
CSRedisClient csredis = new CSRedisClient(configurationSection.Value);
// initialization RedisHelper
RedisHelper.Initialization(csredis);
// register mvc Distributed cache
services.AddSingleton<IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
... Other code
}
- ValuesController.cs
Through static method calls , The key is test1 ,value The value passed from the foreground , cache 60s
Get value Get Method , test1 As key , Return the value to the foreground .60s Get it later , Will not get the value .
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
RedisHelper.Set("test1", value, 60);
}
// GET api/values
[HttpGet]
public ActionResult<string> Get()
{
return RedisHelper.Get("test1");
}
Common mode - Console
class Program
{
static void Main(string[] args)
{
var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,password=,defaultDatabase=CsRedis,prefix=CsRedis_ConSole_Example");
RedisHelper.Initialization(csredis);
RedisHelper.Set("test1", "123123", 60);
string result = RedisHelper.Get("test1");
Console.WriteLine("key:test1,value:" + result);
Console.ReadKey();
}
}
Sentinel mode
Premise
- Understand the role of sentinel mode
- And there is an available master (
master)redisservice , Two slave (slaver) service , There are three sentinels monitoring .
appsettings.jsonConfiguration item
{
"CsRedisConfig": {
"SentinelConnectString": "mymaster,password=,prefix=csredis-example-",
"Sentinel": [
"127.0.0.1:26379",
"127.0.0.1:26380",
"127.0.0.1:26381"
]
}
}
Startup.csThe configuration in is as follows
public void ConfigureServices(IServiceCollection services)
{
//eg.3 Use appsettings.json, Sentinel mode
IConfigurationSection configurationSection = Configuration.GetSection("CsRedisConfig:SentinelConnectString");
string[] sentinelValues = Configuration.GetSection("CsRedisConfig:Sentinel").Get<string[]>();
CSRedisClient csredis = new CSRedisClient(configurationSection.Value, sentinelValues);
// initialization RedisHelper
RedisHelper.Initialization(csredis);
// register mvc Distributed cache
services.AddSingleton<IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
... Other code
}
- Using cache is the same as normal mode , But close one
redisservice , The service is still available , But ifredisIn switchclusterThe process , There will be short-lived failures , But it will recover soon .
RedisHelper And redis-cli The command line is consistent api, Will use redis Relevant command , You can use RedisHelper Method
coordination redis-cli Command line
static void Main()
{
CSRedisClient csredis = new CSRedisClient("127.0.0.1:6379,password=,defaultDatabase=CsRedis,prefix=CsRedis_ConSole_Example");
RedisHelper.Initialization(csredis);
Test();
Console.ReadKey();
}
static void Test()
{
//1.set key value [ex seconds] [px milliseconds] [nx|xx]
//setex key seconds value # Set the value of the key , And specify the... Corresponding to this key value Valid time .
//setnx key value # The key must be non-existent , Can be set successfully . If the key already exists , return 0.
RedisHelper.Set("redis-key", "just a string value", 50);//setex "redis-key" 50 "just a string value"
RedisHelper.Set("redis-key-class",DateTime.Now, 30);
//1.1.2. Get value
//get key
// If you want to get The key doesn't exist , Then return to nil( empty ).
string redisValue = RedisHelper.Get("redis-key");
Console.WriteLine($"setex redis-key 50 just a string value ,RedisHelper.Get() The results are as follows :{
redisValue}");
DateTime now = RedisHelper.Get<DateTime>("redis-key-class");
Console.WriteLine($"setex redis-key-class DateTime.Now,RedisHelper.Get() Values are as follows {
now}");
//1.1.3. Batch setting value
//mset key value [key value ...]
RedisHelper.MSet("a", "1", "b", "2", "c", "3","d","4");// Equivalent to mset a 1 b 2 c 3 d 4
//1.1.4. Batch fetch value
//mget key [key ...]
string[] mgetValues = RedisHelper.MGet<string>("a", "b", "c","d");
Console.WriteLine($"mset a 1 b 2 c 3 d 4, RedisHelper.MGet() The value is ");
foreach (var mgetValue in mgetValues)
{
Console.Write($"{
mgetValue}、");
}
Console.WriteLine();
//1.1.5. Count
//incr key
//incr The command is used to do Self increment operation
// Increment the specified number
long incr = RedisHelper.IncrBy("key");
Console.WriteLine($"incr key, incr The value is {
incr}");
// Set the increment value of the self incrementing number
incr = RedisHelper.IncrBy("key",2);
Console.WriteLine($" Again incrby key 2, incr The value is {
incr}");
incr = RedisHelper.IncrBy("key", -2);
Console.WriteLine($" Again decrby key -2, incr The value is {
incr}");
//exists key
bool isExistsKey = RedisHelper.Exists("new-key");
Console.WriteLine($"exists key ,value:{
isExistsKey}");
double incrByFloat=RedisHelper.IncrByFloat("key-float", 0.1);
Console.WriteLine($"incrbyfloat key-float 0.1,value:{
incrByFloat}");
}
边栏推荐
- [web technology] 1348- talk about several ways to implement watermarking
- 【LeetCode】53. Maximum subarray and
- Report on the "fourteenth five year plan" and strategic strategy recommendations for China's intellectual property protection industry 2022 ~ 2028
- 年薪50万是一条线,年薪100万又是一条线…...
- JVM Basics - > how to troubleshoot JVM problems in your project
- Pat grade A - 1167 Cartesian tree (30 points) (buildtree + level traversal)
- Web3 principle and decentralization
- Analysis report on the "fourteenth five year plan" and the latest development trend of China's medical information industry from 2022 to 2028
- 数据库每日一题---第10天:组合两个表
- Yyds dry inventory insider news: Series high-frequency interview questions, worth a visit!
猜你喜欢

Redis optimization
![[data analysis] data clustering and grouping based on kmeans, including Matlab source code](/img/76/deec6cf60c0d02e99ebc3e21d3b8a4.png)
[data analysis] data clustering and grouping based on kmeans, including Matlab source code

JVM Basics - > how to troubleshoot JVM problems in your project

Alcohol detector based on 51 single chip microcomputer

leetcodeSQL:574. Elected

JVM foundation > G1 garbage collector

Web3 principle and decentralization

The programmer dedicated to promoting VIM has left. Father of vim: I will dedicate version 9.0 to him

The annual salary of 500000 is one line, and the annual salary of 1million is another line

数据库每日一题---第10天:组合两个表
随机推荐
Global and Chinese Melamine Industry Development Research and prospect trend report 2022-2028
管线中的坐标变换
Analysis report on business model innovation path and operation status of China's app store industry from 2022 to 2028
Zabbix的功能介绍和常用术语
Research Report on truffle fungus industry - market status analysis and development prospect forecast
Is it safe to open an account in tonghuashun? How to open an account for securities
反走样/抗锯齿技术
The interface testing tool apipos3.0 is applicable to process testing and reference parameter variables
Introduction to Quaternion
[data analysis] data clustering and grouping based on kmeans, including Matlab source code
[Part 8] semaphore source code analysis and application details [key points]
vim利用右下4键
【LeetCode】102. Sequence traversal of binary tree
MySQL case when then function use
【LeetCode】300.最长上升子序列
JVM foundation - > what is STW?
【LeetCode】剑指 Offer II 020. 回文子字符串的个数
Qt Quick 3D学习:使用鼠标键盘控制节点位置和方向
JVM Basics - > What are the thread shared areas in the JVM
四元数简介