Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the comparison and experience of the three major Redis clients of DotNetCore?

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article shows you what you have learned from the comparison and use of the three major Redis clients of DotNetCore. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Preface

Slightly more complex Internet projects and technology selection will involve the ecological improvement of Redis,.NetCore, and there are more and more Redis clients supporting NetCore.

The following three common Redis clients, I believe we usually use some, combined with the experience of the three clients, some experience.

Compare the macro background first:

Experience in using it

The connection string configurations supported by the three client Redis are basically the same.

"connectionstrings": {

"redis": "localhost:6379,password=abcdef,connectTimeout=5000,writeBuffer=40960"

}

1. StackExchange.Redis

Positioning is a high-performance, general-purpose Redis .net client; it is easy to apply the full function of Redis; supports Redis Cluster

The core of high performance is: multiplexing connections (allowing the efficient use of shared connections from multiple calling threads), server-side operations using the ConnectionMultiplexer class ConnectionMultiplexer redis = ConnectionMultiplexer.Connect ("server1:6379,server2:6379")

/ / the core class library for daily applications is IDatabase

IDatabase db = redis.GetDatabase ()

/ / Pub/Sub is supported

ISubscriber sub = redis.GetSubscriber ()

Sub.Subscribe ("messages", (channel, message) = > {

Console.WriteLine ((string) message)

});

-

Sub.Publish ("messages", "hello")

It is precisely because of multiplexing that the only Redis feature that StackExchange.Redis does not support is "blocking pops", which is the key theory of RedisMQ. If you need blocking pops, StackExchange.Redis officially recommends using the pub/sub model simulation implementation.

For daily operation API, please pay attention to the IDatabase interface and support asynchronous methods. Here I disagree with the statement that "client operation Redis should not use asynchronous methods as far as possible". For asynchronous methods, I think we should follow Microsoft best practices: for IO-intensive operations, use async / / corresponding redis self-increment api:DECR mykey as far as possible.

_ redisDB0.StringDecrementAsync ("ProfileUsageCap", (double) 1)

/ / corresponding redis api:HGET KEY field1

_ redisDB0.HashGetAsync (profileUsage, eqidPair.ProfileId))

/ / corresponding redis hash increment api:HINCRBY myhash field-1

_ redisDB0.HashDecrementAsync (profileUsage, eqidPair.ProfileId, 1)

ConnectionMultiplexer mode supports switching Redis DB at any time. For the operation of multiple Redis DB, I encapsulate a commonly used Redis DB operation client. Public class RedisStore

{

Private static Lazy LazyConnection

Private static string connectionRedis = "localhost:6379"

Public RedisStore (string connectiontring)

{

ConnectionRedis = connectiontring? "localhost:6379"

LazyConnection = new Lazy (() = > ConnectionMultiplexer.Connect (connectionRedis))

}

Public static ConnectionMultiplexer Connection = > LazyConnection.Value

Public RedisDatabase RedisCache = > new RedisDatabase (Connection)

}

Public class RedisDatabase

{

Private Dictionary DataBases = new Dictionary ()

Public ConnectionMultiplexer RedisConnection {get;}

Public RedisDatabase (ConnectionMultiplexer Connection)

{

DataBases = new Dictionary {}

For (var iTuno Bandi)

{

Options.Configuration = Configuration.GetConnectionString ("redis")

Options.InstanceName = "SampleInstance"

});

/ / Set Cache Item (by byte [])

Lifetime.ApplicationStarted.Register (() = >

{

Var currentTimeUTC = DateTime.UtcNow.ToString ()

Byte [] encodedCurrentTimeUTC = Encoding.UTF8.GetBytes (currentTimeUTC)

Var options = new DistributedCacheEntryOptions ()

.SetSlidingExpiration (TimeSpan.FromMinutes (20))

Cache.Set ("cachedTimeUTC", encodedCurrentTimeUTC, options)

});

/ / Retrieve Cache Item

[HttpGet]

[Route ("CacheRedis")]

Public async Task GetAsync ()

{

Var ret = ""

Var bytes = await _ cache.GetAsync ("cachedTimeUTC")

If (bytes! = null)

{

Ret = Encoding.UTF8.GetString (bytes)

_ logger.LogInformation (ret)

}

Return await Task.FromResult (ret)

}

① obviously, this Cache component cannot switch Redis DB freely. At present, you can configure which Redis DB to use for the project at one time in the redis connection string.

② generates a redis cache entry of key = SampleInstancecachedTimeUTC at the specified DB (default is 0)

③ general API only supports passing values in the form of bytes []. The above byte [] is actually stored in the form of Hash.

3. CSRedisCore

This component is based on the connection pool model, and the default configuration warms up 50 redis connections. The function is more flexible, and there are more ways to play for the actual Redis application scenario.

Ordinary mode

Official cluster model redis cluster

Partition mode (implemented by the author)

The method of using normal mode is extremely simple, and here is a hint: the client does not support switching Redis DB at will, but the original author gives a way to alleviate it: to construct multiple clients.

Var redisDB = new CSRedisClient [16]; / / multiple clients

For (var a = 0; a < redisDB.Length; aura +)

RedisDB [a] = new CSRedisClient (Configuration.GetConnectionString ("redis") + ", defaultDatabase=" + a)

Services.AddSingleton (redisDB)

/ /--

_ redisDB [0] .IncrByAsync ("ProfileUsageCap",-1)

_ redisDB [0] .HGetAsync (profileUsage, eqidPair.ProfileId.ToString ())

_ redisDB [0] .HIncrByAsync (profileUsage, eqidPair.ProfileId.ToString (),-1)

The built-in static operation class RedisHelper is exactly the same as the Redis-Cli command, so it can natively support "blocking pops".

/ / implement backend service to consume MQ messages continuously

Public class BackgroundJob: BackgroundService

{

Private readonly CSRedisClient [] _ redisDB

Private readonly IConfiguration _ conf

Private readonly ILogger _ logger

Public BackgroundJob (CSRedisClient [] csRedisClients,IConfiguration conf,ILoggerFactory loggerFactory)

{

_ redisDB = csRedisClients

_ conf = conf

_ logger = loggerFactory.CreateLogger (nameof (BackgroundJob))

}

/ / background tasks that need to be implemented in Background

Protected override async Task ExecuteAsync (CancellationToken stoppingToken)

{

_ redisDB [0] = new CSRedisClient (_ conf.GetConnectionString ("redis") + ", defualtDatabase=" + 0)

RedisHelper.Initialization (_ redisDB [0])

While (! stoppingToken.IsCancellationRequested)

{

Var key = $"eqidpair: {DateTime.Now.ToString (" yyyyMMdd ")}"

/ / blocking to read the first List message from the right

Var eqidpair = RedisHelper.BRPop (5, key)

/ / TODO Handler Message

Else

Await Task.Delay (1000, stoppingToken)

}

}

}

-RedisMQ producer--

/ / insert one or more msg into the List header

RedisHelper.LPush (redisKey, eqidPairs.ToArray ())

There is still a big gap between the positioning of the above three major clients, Microsoft.Extensions.Caching.StackExchangeRedis and the other two. If you simply use the Redis cache feature and are produced by Microsoft, you can use this client if it is a boutique complex.

Comparison of StackExchange.Redis and CSRedisCore's support for Redis full-featured features

A little experience of Redis

Be aware of the time complexity of the Redis API to be used. Try not to use long-running commands such as keys *. You can observe which commands take a long time through the redis.io SlowLog command

Redis Key can be separated and defined into business meaningful strings such as NewUsers:202004:666 (some Redis UI can view the key value intuitively and amicably) by ":"

Determine the size of Key-Value appropriately: Redis is more friendly to small value. If the value is large, consider dividing it into multiple key

As for cache penetration, you will ask during the interview and search the Bloom filter on your own.

Although redis has a persistence mechanism, it actually persists key-value to relational databases because SQL is more efficient for some structured queries.

The above is the experience of comparing and using the three major Redis clients of DotNetCore. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report