>  기사  >  데이터 베이스  >  Go에서 redis와 redigo를 작동하는 방법

Go에서 redis와 redigo를 작동하는 방법

WBOY
WBOY앞으로
2023-05-30 21:25:10980검색

Go-operate redis

Installation

golang에는 redigo 및 go-redis와 같은 redis 운영을 위한 여러 클라이언트 패키지가 있습니다. github에서 가장 많은 별을 받은 것은 redigo입니다.

go get github.com/garyburd/redigo/redis
import "github.com/garyburd/redigo/redis"

Connection

Conn 인터페이스는 Redis와의 협업을 위한 기본 인터페이스입니다. Dial, DialWithTimeout 또는 NewConn 함수를 사용하여 작업이 완료되면 애플리케이션이 작업을 완료하기 위해 Close 함수를 호출해야 합니다. .

package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
}

package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
    _, err = conn.Do("SET", "name", "wd")
    if err != nil {
        fmt.Println("redis set error:", err)
    }
    name, err := redis.String(conn.Do("GET", "name"))
    if err != nil {
        fmt.Println("redis get error:", err)
    } else {
        fmt.Printf("Got name: %s \n", name)
    }
}

를 사용하여 키 만료 시간을 설정하세요.

  _, err = conn.Do("expire", "name", 10) //10秒过期
    if err != nil {
        fmt.Println("set expire error: ", err)
        return
    }

Batch get mget, 일괄 설정 mset

_, err = conn.Do("MSET", "name", "wd","age",22)
    if err != nil {
        fmt.Println("redis mset error:", err)
    }
    res, err := redis.Strings(conn.Do("MGET", "name","age"))
    if err != nil {
        fmt.Println("redis get error:", err)
    } else {
        res_type := reflect.TypeOf(res)
        fmt.Printf("res type : %s \n", res_type)
        fmt.Printf("MGET name: %s \n", res)
        fmt.Println(len(res))
    }
//结果:
//res type : []string 
//MGET name: [wd 22] 
//2

List 작업

package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
    "reflect"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
    _, err = conn.Do("LPUSH", "list1", "ele1","ele2","ele3")
    if err != nil {
        fmt.Println("redis mset error:", err)
    }
    res, err := redis.String(conn.Do("LPOP", "list1"))
    if err != nil {
        fmt.Println("redis POP error:", err)
    } else {
        res_type := reflect.TypeOf(res)
        fmt.Printf("res type : %s \n", res_type)
        fmt.Printf("res  : %s \n", res)
    }
}
//res type : string 
//res  : ele3

hash 작업

package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
    "reflect"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
    _, err = conn.Do("HSET", "student","name", "wd","age",22)
    if err != nil {
        fmt.Println("redis mset error:", err)
    }
    res, err := redis.Int64(conn.Do("HGET", "student","age"))
    if err != nil {
        fmt.Println("redis HGET error:", err)
    } else {
        res_type := reflect.TypeOf(res)
        fmt.Printf("res type : %s \n", res_type)
        fmt.Printf("res  : %d \n", res)
    }
}
//res type : int64 
//res  : 22

파이프라이닝(파이프라이닝)

Send(), Flush( ) 및 Receiver() 세 가지 메서드는 동시에 파이프라인 작업을 수행할 수 있습니다. 클라이언트는 send() 메소드를 사용하여 하나 이상의 명령을 서버에 한 번에 보낼 수 있습니다. 명령이 전송되면 플러시() 메소드를 사용하여 버퍼에 입력된 명령을 클라이언트에 한 번에 보냅니다. 그런 다음 수신() 메서드를 순서대로 사용하여 모든 명령 작업 결과를 선입선출 순서로 읽습니다.

Send(commandName string, args ...interface{}) error
Flush() error
Receive() (reply interface{}, err error)
  • Send: 버퍼에 명령 보내기

  • Flush: 버퍼를 지우고 서버에 명령 보내기

  • Recevie: 읽기 명령이 실행될 때 서버 응답 결과를 순차적으로 읽습니다. 응답하지 않으면 작업이 차단됩니다.

package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
    conn.Send("HSET", "student","name", "wd","age","22")
    conn.Send("HSET", "student","Score","100")
    conn.Send("HGET", "student","age")
    conn.Flush()
    res1, err := conn.Receive()
    fmt.Printf("Receive res1:%v \n", res1)
    res2, err := conn.Receive()
    fmt.Printf("Receive res2:%v\n",res2)
    res3, err := conn.Receive()
    fmt.Printf("Receive res3:%s\n",res3)
}
//Receive res1:0 
//Receive res2:0
//Receive res3:22

redis 릴리스 구독 모드

package main
import (
    "github.com/garyburd/redigo/redis"
    "fmt"
    "time"
)
func Subs() {  //订阅者
    conn, err := redis.Dial("tcp", "10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :", err)
        return
    }
    defer conn.Close()
    psc := redis.PubSubConn{conn}
    psc.Subscribe("channel1") //订阅channel1频道
    for {
        switch v := psc.Receive().(type) {
        case redis.Message:
            fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
        case redis.Subscription:
            fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
        case error:
            fmt.Println(v)
            return
        }
    }
}
func Push(message string)  { //发布者
    conn, _ := redis.Dial("tcp", "10.1.210.69:6379")
    _,err1 := conn.Do("PUBLISH", "channel1", message)
       if err1 != nil {
             fmt.Println("pub err: ", err1)
                 return
            }

}
func main()  {
    go Subs()
    go Push("this is wd")
    time.Sleep(time.Second*3)
}
//channel1: subscribe 1
//channel1: message: this is wd

트랜잭션 작업

MULTI, EXEC, DISCARD 및 WATCH는 Redis 트랜잭션의 기본입니다. 물론 Go 언어를 사용하여 Redis에서 트랜잭션 작업을 수행할 때는 기본적으로 이러한 명령을 사용합니다. .

MULTI: 거래 시작

EXEC: 거래 실행

DISCARD: 거래 취소

WATCH: 거래의 주요 변경 사항을 모니터링하고 변경 사항이 있으면 거래를 취소합니다.

예:

package main
import (
"github.com/garyburd/redigo/redis"
"fmt"
)
func main()  {
    conn,err := redis.Dial("tcp","10.1.210.69:6379")
    if err != nil {
        fmt.Println("connect redis error :",err)
        return
    }
    defer conn.Close()
    conn.Send("MULTI")
    conn.Send("INCR", "foo")
    conn.Send("INCR", "bar")
    r, err := conn.Do("EXEC")
    fmt.Println(r)
}
//[1, 1]

범용 작업

Connect redis

conn,err := redis.Dial(
  "tcp",
  "10.0.3.100:6379",
  redis.DialPassword("EfcHGSzKqg6cfzWq"),
  redis.DialDatabase(8))
if err != nil {
  fmt.Println("connect redis error :",err)
  return
}
defer conn.Close()

Write

//写入
//_, err = conn.Do("LPUSH", "list1", "ele1","ele2","ele3")
_, err = conn.Do("reids写入方法", "key名字", "内容1","内容2","内容3")
if err != nil {
  fmt.Println("redis set error:", err)
}

Read

//读取
redis.Strings:返回多个
redis.String:返回一个
redis.int:返回统计的数字
//获取集合所有成员
//name, err := redis.Strings(conn.Do("smembers", "beautiful_user"))
// 返回集合成员数
//name, err := redis.Int(conn.Do("scard", "beautiful_user"))
name, err := redis.方法名(conn.Do("redis读取方法", "key名字"))
if err != nil {
  fmt.Println("redis get error:", err)
} else {
  fmt.Printf("Got name: %s \n", name)
}

전체 코드

package main
import (
	"fmt"
	"github.com/garyburd/redigo/redis"
)
func main()  {
	conn,err := redis.Dial("tcp","10.0.3.100:6379",redis.DialPassword("EfcHGSzKqg6cfzWq"),redis.DialDatabase(8))
	if err != nil {
		fmt.Println("connect redis error :",err)
		return
	}
	defer conn.Close()
	//写入
	_, err = conn.Do("LPUSH", "list1", "ele1","ele2","ele3")
	if err != nil {
		fmt.Println("redis set error:", err)
	}
	//读取
	name, err := redis.Strings(conn.Do("smembers", "beautiful_user"))
	if err != nil {
		fmt.Println("redis get error:", err)
	} else {
		fmt.Printf("Got name: %s \n", name)
	}
}

위 내용은 Go에서 redis와 redigo를 작동하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제