Redis
It is a very common application developmentNoSQL
Database, as an in-memory database,Redis
Supports data persistence (RDB
andAOF
Two mechanisms), soRedis
It can be used as a database or as a cache between a relational database and an application.
So how to connect and operate in GoRedis
Woolen cloth? In this article, let’s explore it together!
start
Start operationRedis
Before, we will initialize our sample project and then install the connectionRedis
The required third-party library.
Initialize the project
Since the third-party library we will use next requiresGo Moudles
support, so we usego mod init
Command initializes our sample project:
go mod init GoTest
Go Redis
Since the Go language standard library does not provide anyRedis
support, so you need to use itGo
The community's third-party library.
Recommended hereGo Reids
, the latest version of this libraryGithub
Address:
/redis/go-redis
Why Go Redis is recommended
Recommended useGo Redis
The reasons are as follows:
-
Go Redis
yesRedis
Officially recommended third-party library. - There are also many people in the community and the documentation is very complete.
- Supports different kinds of
Redis
Clients, such as Sentinel Clients, cluster clients, etc. - Support all
Redis
Version.
Go Redis installation
passcd
The command enters the project and executesgo get
You can download and install it by command/redis/go-redis/v9
:
cd GoTest #The latest version is v9go get /redis/go-redis/v9
Connect to Redis
As with allClient/Server
Like the application, if you want to operate itRedis
, you must firstRedis
Establish a network connection.
Simple connection
If the connection is deployed on the internal network, there is no passwordRedis
Server, onlyIP
andPort number (port)
You can connect:
import "/redis/go-redis/v9" opt := &{ Addr: "localhost:6379", } rdb := (opt)
In the above code, you can outline the following two steps:
- Instantiate a
Indicates the connection configuration object, which is currently set
Addr
field, the field representsRedis
The address of the server. - Will
Transfer the object to
()
function,()
The function returns an operationRedis
Handle ofrdb
。
In addition to customization, another way is to call
()
Function in the following formatURL
, the function returns aObject:
redis://<user>:<pass>@localhost:6379/<port>
So we can connect the aboveRedis
The example is rewritten as:
import "/redis/go-redis/v9" opt, err := ("redis://localhost:6379") if err != nil { panic(err) } rdb := (opt)
We connect beforeRedis
Only used in the exampleof
Addr
Fields:
opt := &{ Addr: "localhost:6379", }
In addition, we can alsoThe fields to configure the connection parameters:
opt := &{ //Address and port Addr: "localhost:6379", //Database, 0~16 DB:0, //User name, used on Redis 6.0 or above Username:"test", //password Password:"123456", //Maximum number of retry times for command MaxRetries:3, //Connection timeout DialTimeout:3, //Connection pool PoolSize:30, //Minimum number of idle connections MinIdleConns:10, //Maximum number of idle connections MaxIdleConns:30, }
The above list isThere are actually many other field parameters for more commonly used fields, so I won't list them one by one here.
Redis Operation
Although it has passed()
Function obtaining operationRedis
handle, but need to operateRedis
, need to create oneContext
Object, this is because of allGo Redis
operateRedis
The first parameter of the method isContext
。
Create a Context
Context
Represents the context, which can be used for timeout control, data delivery, performance monitoring, etc.
passcontext
PackedBackgroud()
Functions can create a rootContext
:
ctx := ()
Execute supported commands
Go Redis
For allRedis
The commands provide corresponding methods, such asSET
The corresponding method of the command isSet
,HGET
The corresponding method isHGet
。
Therefore, if you want to execute the correspondingRedis
Command, just call the corresponding method directly, such as:
redis> set test test_value 0 redis> hset user:1 id 1 name Xiao Zhang gender male
useGo Redis
The code to execute the above command is:
(ctx, "test", "test_value", 0) (ctx, "user:1", "id",1,"name", "Xiao Zhang", "gender", "male")
Redis
After the command is executed, there are usually returns, but the return values of different commands are different. The simplest return isSET
The command returns a string.HSET
The command returns an integer, andHGETALL
A structure-like data will be returned:
package main import ( "context" "fmt" "/redis/go-redis/v9" ) func main() { rdb := (&{ Addr: "localhost:6379", }) ctx := () setCmd := (ctx, "test", "test_value", 0) hSetCmd := (ctx, "user:1", "id", 1, "name", "Xiao Zhang", "gender", "male") hAllGetCmd := (ctx, "user:1") }
In the above code, we can see that when executing different commands, different returns will be returnedcmd
Objects, such asSet()
Method returns aStatusCmd
Object,HSet()
Method returnIntCmd
object, andHGetAll()
Method returnMapStringStringCmd
Object.
Have itcmd
After the object, you can get the command execution result and error information. There are two methods, one is to call it directly.Result()
The method returns the result and error message:
(()) (()) (())
Another way is to get the result and error message separately:
((),()) ((),()) ((),())
The results of the above two output methods are:
OK <nil>
3 <nil>
map[gender:male id:1 name:Xiao Zhang] <nil>
If we get a non-existent key, the command will return a special error, This is a special error to indicate whether a null value was obtained:
val, err := (ctx, "key").Result() switch { case err == : ("Key does not exist") case err != nil: ("mistake", err) case val == "": ("The value is an empty string") }
Execute commands that are not yet supported
Of course, sometimesRedis
The new version may add some new commands, andGo Redis
Support has not been provided yet, you can call it at this timeDo
Methods to execute the corresponding commands, in factDo()
Methods can be used to execute any command:
val, err := (ctx, "hgetall", "user:1").Result() if err != nil { if err == { ("key does not exists") return } panic(err) } (val.(MapStringStringCmd))
From the above example, we can seeDo()
The return value is also different after executing different commands.
Result Set Mapping
Sometimes we will return multiple items after querying Rediskey-value
The result set, e.g.mget
、hget
,hgetall
Such a commandGo redis
ProvidedScan()
The method can scan the queryed result set into the corresponding structure:
package main import ( "context" "fmt" "/redis/go-redis/v9" ) type User struct { ID int `redis:"id"` Name string `redis:"name"` Gender string `redis:"gender"` } func main() { rdb := (&{ Addr: "localhost:6379", }) ctx := () var u User err := (ctx, "user:1").Scan(&u) if err != nil { panic(err) } (u) }
pipeline
Pipeline
Allows multiple messages to be sent in a single requestRedis
Command and return multiple results, which can save the return time required to execute commands one by one:
package main import ( "context" "fmt" "/redis/go-redis/v9" ) func main() { opt := &{ Addr: "localhost:6379", } rdb := (opt) ctx := () cmds, err := (ctx, func(pipe ) error { (ctx, "test", "test_value", 0) (ctx, "user:1", "id", 1, "name", "Xiao Zhang", "gender", "male") (ctx, "user:1") return nil }) if err != nil { panic(err) } for _, cmd := range cmds { switch c := cmd.(type) { case *: (()) case *: (()) case *: (()) } } }
Publish and Subscribe
Go Redis
Support publishing and subscription (Pub/Sub
)。
Post a message
The method of posting a message isPublish
:
package main import ( "context" "fmt" "/redis/go-redis/v9" ) func main() { rdb := (&{ Addr: "localhost:6379", }) ctx := () //Send messages to the channel err := (ctx, "mychannel", "this is a message").Err() if err != nil { panic(err) } }
Subscribe to Message
The method to subscribe to a message isSubscribe
, after subscribing, call it through the returned handleReceiveMessage()
Method to receive messages:
package main import ( "context" "fmt" "/redis/go-redis/v9" ) func main() { rdb := (&{ Addr: "localhost:6379", }) ctx := () pubsub := (ctx, "mychannel") defer () //Receive message for { msg, err := (ctx) if err != nil { panic(err) } ("Receive %s from the %s channel", , ) } }
summary
In this article, we explain/redis/go-redis
The basic operations of connecting and operating Redis are actually supported. In fact, this library supports many advanced functions, such as sentinels, clusters, sharding and other functions. I will explain it in other articles in the future.
The above is the detailed content of how to use Redis when learning Go language. For more information about Go Redis, please follow my other related articles!