There is a demo download at the end of the article


Is Redis difficult to use? B: No, is Redis easy to use? Is not easy.

Redis is an open source key-value store, but not just a key-value store. According to the official website, Redis is a data structure store that can be used as a database, cache, and messaging middleware. Compared to traditional key-value storage Memcached, Redis has the following features:

  • Speed is fast

  • In addition to String, there is also a List, Hash, Set, Sorted Set

  • Single thread, avoiding the performance cost of thread switching and locking

  • Atomic operation

  • Persistency (RDB and AOF)

  • Publish/subscribe

  • Support for Lua scripts

  • A distributed lock

  • The transaction

  • Master slave Replication and High Availability (Redis Sentinel)

  • Clustering (version 3.0 and above)

    1, the String

    This is the simplest Redis type. Using only this type, Redis is like a persistent Memcached server.

    2, the List

    Redis lists are based on bidirectional linked lists, which support reverse lookup and traversal.

    Common cases: chat system, social network to get the latest posts published by users, simple message queue, news paging list, blog comment system.

    3, the Hash

    Hash is a mapping table between fields and values of type String, as shown in the figure below. Hashtable and Dictionary in NET. It is used to store objects, avoiding serialization overhead and concurrent modification control.

    4, the Set

    A Set is also a list, but it is special because it can be automatically de-weighted: it is a good choice when you need to store a list of data and you don’t want to duplicate it (such as a collection of ids). And Set provides an interface for determining whether a member is in a Set, which List does not.

    5, Sorted Set

    Sorted Set and Set are used in similar scenarios, except that Sorted Set is automatically Sorted based on the score parameter provided. When you need an ordered and non-repetitive list of collections, choose the Sorted Set data structure. Common examples: leaderboards in games.

    The following features focus on pipes and transactions.

    1, pipes,

    The Redis pipeline means that the client can send multiple commands to the server at once, and the server can return all the results at once. Pipeline technology can greatly reduce the cost of network transmission and improve performance when executing commands in batches.

    2, transaction

    A Redis transaction is a collection of commands. Either all commands in a transaction are executed or none are executed. If an error occurs during a command run, it is not automatically rolled back.

    The difference between pipes and transactions: Pipes are mainly optimized on the network. The client buffers a set of commands and sends them to the server for execution at one time, but there is no guarantee that the commands will be executed in the same transaction. Transactions are atomic, ensuring that no commands from other clients are inserted into the command sequence during command execution.

    3. Distributed locks

    Distributed locking is a way to control synchronous access to shared resources between distributed systems. In a distributed system, often need to coordinate their movements, if different systems or the same system between different host Shared a or a set of resources, so access to these resources, often require a mutex to prevent interference with each other to ensure consistency, in this case, the need to use to distributed lock.

    4. Geographic information

    Starting with Version 3.2 of Redis, geolocation commands have been added to store and manipulate user-given geolocation information (latitude and longitude).

    Step 1 Reference fxcommon.dll and Redis. DLL in projects that need to use Redis.

    Step 2 Add the following configuration to the app. config or web. config file:

    < the add key = "RedisServerIP" value = "redis: [email protected]:4125" / > <! The Redis environment provided is a standalone configuration. If Redis is a master/slave configuration, you need to set RedisSlaveServerIP--> <! - < the add key = "RedisSlaveServerIP" value = "redis: [email protected]:4125" / > -- > <! --Redis database. <add key="RedisDefaultDb" value="0"/>Copy the code

    Create Redis connection pool with PooledRedisClientManager class

    // Reading the Redis host IP configuration information String [] redisMasterHosts = ConfigurationManager.ConnectionStrings["RedisServerIP"].ConnectionString.Split(','); String [] redisSlaveHosts = null; string[] redisSlaveHosts = null; var slaveConnection = ConfigurationManager.ConnectionStrings["RedisSlaveServerIP"]; if (slaveConnection ! = null && ! string.IsNullOrWhiteSpace(slaveConnection.ConnectionString)) { string redisSlaveHostConfig = slaveConnection.ConnectionString; redisSlaveHosts = redisSlaveHostConfig.Split(','); } // read RedisDefaultDb config int defaultDb = 0; string defaultDbSetting = ConfigurationManager.AppSettings["RedisDefaultDb"]; if (! string.IsNullOrWhiteSpace(defaultDbSetting)) { int.TryParse(defaultDbSetting, out defaultDb); } var redisClientManagerConfig = new RedisClientManagerConfig { MaxReadPoolSize = 50, MaxWritePoolSize = 50, DefaultDb = defaultDb }; Manager = new PooledRedisClientManager(redisMasterHosts, redisSlaveHosts, redisClientManagerConfig) { PoolTimeout = 2000, ConnectTimeout = 500 };Copy the code

    Step 4. Get the Redis client from an instance of PooledRedisClientManager and start working with the Redis client API.

    5.1 Redis Key naming specification

    Redis Key naming conventions: AppID:KeyName.

    The AppID and KeyName should be separated by a colon instead of a dot. The Redis Key will be displayed in the Redis Desktop Manager as an AppID, so that you can quickly check the Redis Key corresponding to the Redis Value, please see the following figure:

    Redis keys will not be classified in Redis Desktop Manager if they are separated by dots. See the following figure:

    5.2 Common Application Problems

    • Cache penetration processing: What is cache penetration? When the Redis key is queried in the cache and there is no corresponding Value, it should be searched in the back-end system such as DB. Once the number of concurrent requests for this key increases, it will cause great pressure on DB. The solutions are as follows: a. Front-end risk control, excluding malicious penetration; B. If the query result is empty, the system still caches the query result, but the cache time is set to a short time, usually several minutes.

    • Cache avalanche handling: What is a cache avalanche? When the cache server restarts or a large number of caches fail in a certain period of time, the failure will also put a lot of pressure on the back-end system (such as DB). The solutions are: back-end connection number limit, error threshold limit, timeout handling, uniform distribution of cache expiration time, front-end invalidation and back-end active update.

    • Cache duration: Policy positioning is complex and requires multi-dimensional calculation.

    • Cache invalidation: time invalidation, event invalidation, active backend update.

    • Cache Key: Hash, rule, prefix +Hash. Manual intervention can be performed when exceptions occur.

    • Lua scripts: server batch processing and transaction capabilities, conditional logic extensible scripts. The advantages of using it are: reduced network overhead, atomic operations, reusable.

    • Limit: sliding the time window. If it is used in a Session, Memcached transfers the Key and Value each time.

      • RedisDemo download address:

        https://github.com/das2017/RedisDemo

      • RedisDesktopManage

        https://redisdesktop.com/

      • Redis website:

        https://redis.io/

      • ServiceStack.Redis client:

        https://github.com/ServiceStack/ServiceStack.Redis

      • Redis:

        http://www.redis.cn/commands.html

      The list of topics covered in this series is as follows. If you are interested, please pay attention:

      • Opening:Small and medium-sized R&D team architecture practice three points

      • Cache Redis

      • Message queue RabbitMQ:How to use the good news queue RabbitMQ?

      • Centralized log ELK

      • Task scheduling Job:Task scheduling in small and medium-sized R&D team architecture practice

      • Apply monitoring Metrics:How does application monitoring work?

      • Microservices framework MSA

      • Solr

      • Distributed coordinator ZooKeeper

      • Small tools:

        Dapper.NET/EmitMapper/AutoMapper/Autofac/NuGet

      • Release tool Jenkins

      • Overall architecture design:How does e-commerce make the overall structure of the enterprise?

      • Single project architecture design

      • Unified application stratification:How to standardize all application layers in the company?

      • Debugging tool WinDbg

      • Single sign-on (sso)

      • Enterprise Payment Gateway

      • “Article

      Zhang Huiqing, an IT veteran of more than 10 years, has successively served as architect of Ctrip, chief architect of Gooda Group, CTO of Zhongqing E-Travel and led the upgrading and transformation of the technical architecture of the two companies. Focus on architecture and engineering efficiency, technology and business matching and integration, technology value and innovation.

      Yang Li has years of experience in Internet application system research and development. She used to work in Gooda Group and now works as the system architect of Zhongqing E-Travel. She is mainly responsible for the architecture design of the business system of the company’s R&D center, as well as the accumulation and training of new technologies. The current focus is on open source software, software architecture, microservices and big data.

      Task scheduling in small and medium-sized R&D team architecture practice

      Microservice authentication based on STS and JWT

      How does application monitoring work?


      International architecture Architecture, big data platform architecture, microservices architecture, database architecture, etc. At the Global Architect Summit, We invite senior architects from Microsoft, Google, Facebook, Twitter, Uber, Tumblr, Twitch, Snapchat and others to answer your questions one by one. At present, there are hundreds of technical cases in the 10% discount registration, welcome to click to read the original text to understand.