SoFunction
Updated on 2025-03-05

How to use Redis after learning Go

RedisIt is a very common application developmentNoSQLDatabase, as an in-memory database,RedisSupports data persistence (RDBandAOFTwo mechanisms), soRedisIt can be used as a database or as a cache between a relational database and an application.

So how to connect and operate in GoRedisWoolen cloth? In this article, let’s explore it together!

start

Start operationRedisBefore, we will initialize our sample project and then install the connectionRedisThe required third-party library.

Initialize the project

Since the third-party library we will use next requiresGo Moudlessupport, so we usego mod initCommand initializes our sample project:

go mod init GoTest

Go Redis

Since the Go language standard library does not provide anyRedissupport, so you need to use itGoThe community's third-party library.

Recommended hereGo Reids, the latest version of this libraryGithubAddress:

/redis/go-redis

Why Go Redis is recommended

Recommended useGo RedisThe reasons are as follows:

  • Go RedisyesRedisOfficially recommended third-party library.
  • There are also many people in the community and the documentation is very complete.
  • Supports different kinds ofRedisClients, such as Sentinel Clients, cluster clients, etc.
  • Support allRedisVersion.

Go Redis installation

passcdThe command enters the project and executesgo getYou 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/ServerLike the application, if you want to operate itRedis, you must firstRedisEstablish a network connection.

Simple connection

If the connection is deployed on the internal network, there is no passwordRedisServer, onlyIPandPort 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 aIndicates the connection configuration object, which is currently setAddrfield, the field representsRedisThe address of the server.
  • WillTransfer the object to()function,()The function returns an operationRedisHandle 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 aboveRedisThe example is rewritten as:

import "/redis/go-redis/v9"
opt, err := ("redis://localhost:6379")
if err != nil {
 panic(err)
}
rdb := (opt)

We connect beforeRedisOnly used in the exampleofAddrFields:

opt := &{
 Addr:   "localhost:6379",
}

In addition, we can alsoThe fields to configure the connection parameters:

opt := &amp;{
  //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 operationRedishandle, but need to operateRedis, need to create oneContextObject, this is because of allGo RedisoperateRedisThe first parameter of the method isContext

Create a Context

ContextRepresents the context, which can be used for timeout control, data delivery, performance monitoring, etc.

passcontextPackedBackgroud()Functions can create a rootContext:

ctx := ()

Execute supported commands

Go RedisFor allRedisThe commands provide corresponding methods, such asSETThe corresponding method of the command isSetHGETThe corresponding method isHGet

Therefore, if you want to execute the correspondingRedisCommand, just call the corresponding method directly, such as:

redis&gt; set test test_value 0
redis&gt; hset user:1 id 1 name Xiao Zhang gender male

useGo RedisThe code to execute the above command is:

(ctx, "test", "test_value", 0)
(ctx, "user:1", "id",1,"name", "Xiao Zhang", "gender", "male")

RedisAfter the command is executed, there are usually returns, but the return values ​​of different commands are different. The simplest return isSETThe command returns a string.HSETThe command returns an integer, andHGETALLA structure-like data will be returned:

package main
import (
 "context"
 "fmt"
 "/redis/go-redis/v9"
)
func main() {
 rdb := (&amp;{
  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 returnedcmdObjects, such asSet()Method returns aStatusCmdObject,HSet()Method returnIntCmdobject, andHGetAll()Method returnMapStringStringCmdObject.

Have itcmdAfter 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, sometimesRedisThe new version may add some new commands, andGo RedisSupport has not been provided yet, you can call it at this timeDoMethods 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-valueThe result set, e.g.mgethgethgetallSuch a commandGo redisProvidedScan()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

PipelineAllows multiple messages to be sent in a single requestRedisCommand 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 := &amp;{
  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 RedisSupport 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 := (&amp;{
  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 := (&amp;{
  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-redisThe 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!