The main task of working on Friday is to use redis to handle a queue problem on the old company's platform. By the way, I reviewed the basic knowledge of redis operation. After I came back, I thought about using redis to optimize some usage scenarios in my blog demo and learn how to use redis under golang development.
A brief introduction to Redis
Introduction
The discussion about Redis is actually a cliché issue in the current backend development, and is basically a basic examination point for backend development interviews. The background introduction and detailed description of Redis will not be described here. No matter how you introduce it, the core is that Redis is a memory-based key-value multi-data structure storage and can provide persistent services. Memory-based characteristics determine that Redis is naturally suitable for high-concurrency data read and write cache optimization, and it also brings about excessive memory overhead. So in some specific situations, Redis is a powerful weapon that is always bad, worthy of in-depth learning.
A difficulty or entry point in learning Redis is my personal feeling lies in the change in the concept of object storage. When I first came into contact with Redis, I just graduated from college and my mind was basically full of the concept of relational data storage. When I used it, I always wanted to rely on the relationships within the data to establish connections between data, which was very difficult to use. Later, I gradually got started and felt some of the benefits of operations. For example, for example, if you query a user's comments under an article, the idea of using sql is to search for data matching the user ID and the article ID in the comment table. Sometimes you also need to jointly query other information. However, if it is a Redis operation, the user comments can be quickly retrieved with the 'prefix: Article ID: User ID', for example 'comment:666:888', which is very convenient. Redis is far more powerful than that, and can be slowly experienced in practice.
Main data structure
Redis mainly has five basic data structures, which meet the needs of most cache structures. If you feel awkward when using one structure to store, it is very likely that you have chosen the wrong storage structure. You can consider the correct implementation of other structures.
- String, can be a string, integer, and floating point number. If it is serialized data and involves modification operations, string is not recommended. You can consider using Hash
- Hash, key-value object, can store object data, such as user information.
- List, an ordered data collection, elements can be repeated,
LPUSH
、LPOP
、RPUSH
、RPOP
Combination of other instructions can implement stack and queue operations. - Set, unordered set, elements unique.
- Sorted Set, an ordered version of Sort, can set Score values to determine element sorting, which is suitable for business scenarios such as user ranking.
Common usage scenarios
- High concurrency data cache. For example, in a certain scenario, writing a large number of logs to the database simultaneously will put huge pressure on the server. At this time, you can first write data to redis, and then write it to the database by redis to reduce the pressure of simultaneous writing.
- Hot information is displayed quickly. Suppose there is a news homepage now that you need to quickly display 20 hot news in each column. If you query the database directly, a large number of database requests will be consumed when a large number of users access it at the same time. At this time, redis can be used to optimize. When the news is entered, the title, time and source are written into redis. When the client accesses, the hot news list of the day can be retrieved from the memory at one time, greatly improving the request speed and saving server overhead.
- Save session information. You can cache the user information after login to redis and set the key expiration time at the same time. In this way, when the background API filters the request, user information can be read from memory. Moreover, the expiration mechanism of redis naturally supports verification of the user's identity validity period, which is very convenient to use.
- Statistical count. For example, a common function in the system is to limit the number of logins or all requests within a fixed time period of the same user. At this time, the user id can be used as the key and the number of times is value to cache the counting information, and the INCRBY command natively supports it.
- other. Redis's application scenarios are very wide, including queues, publishing subscriptions, statistical analysis, etc. You can check out the introductions of other articles.
Golang Connect Redis
A major intuitive feeling of using Golang to develop is that basically, the development problems you encounter in daily life are all official or third-party packages to help you implement. At the same time, these packages are open source. As long as you are interested, you can go deep into the internal implementation of the package to learn and understand the implementation ideas and methods of the package. Of course, there are pros and cons. The instability and uneven quality of the third package also increase some development costs. At present, it still feels that the benefits outweigh the disadvantages. Researching the implementation of the source code of the package is also my current learning direction.
garyburd/redigo package introduction
garyburd/redigo
Package is a high-star Redis connection package recommended by many blog posts on the Internet, but when I go to the project address of Github myselfgaryburd/redigo When viewing the API above, I found that the project is currently in archive status, and the project has been moved to gomodule/redigo, and the package acquisition has been naturally changed to go get /gomodule/redigo/redis
This is not the first time I have felt the instability of third-party packages. When I used dep to manage packages, I encountered the problem of conflict between the package version pulled by dep and the local package version API. I have time to talk about this separately. In short, regardless of the detailed differences between these two packages, the following will refer to the new package and introduce the use of the redigo package.
Establish a connection pool
The Redigo Pool structure maintains a Redis connection pool. The application calls the Get method to get the connection from the pool and uses the connected Close method to return the connected resource to the pool. Generally, we declare a global connection pool when the system is initialized, and then obtain the connection when redis is needed and execute instructions.
pool := &{ MaxIdle: 3, /*Maximum number of idle connections*/ MaxActive: 8, /*Maximum number of activated connections*/ Dial: func() (, error) { c, err := ("tcp", 'Link address, for example 127.0.0.1:6379', ('password')) if err != nil { return nil, err } return c, nil } } c:=() defer ()
Execute instructions
Check the source code and discoverConn
The interface has a common method to execute Redis commands:
``` //gomodule/redigo/redis/ // Conn represents a connection to a Redis server. type Conn interface { // Close closes the connection. Close() error // Err returns a non-nil value when the connection is not usable. Err() error // Do sends a command to the server and returns the received reply. Do(commandName string, args ...interface{}) (reply interface{}, err error) // Send writes the command to the client's output buffer. Send(commandName string, args ...interface{}) error // Flush flushes the output buffer to the Redis server. Flush() error // Receive receives a single reply from the Redis server Receive() (reply interface{}, err error) } ```
/commandsThe Redis command reference in the Redis command lists available commands. The do parameters are the same as the redis-cli command parameters, for exampleSET key value EX 360
The corresponding function call isDo("SET", "key", "value","EX",360)
, Commonly used command examples are:
c:=() defer () //Save value,_, err := ("SET", "key", "value") //Set expiration time_, err := ("SET", "key", "value","EX",360) //Save int_, err := ("SET", "key", 2) //Get the valuev,err:=(("GET","key")) bytes, err := (("GET", "key"))
Summarize
It is relatively simple to connect and use redis in golang, so there is nothing else to say at the moment. If you find any omissions during your use later, add it. The key is to be familiar with it. redis-cli
Native command operations.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.