Go-Operation redis
Installation
There are multiple client packages for golang to operate redis, such as redigo and go-redis. The one with the most stars on github is redigo.
go get github.com/garyburd/redigo/redis import "github.com/garyburd/redigo/redis"
Connection
The Conn interface is the main interface for collaboration with Redis. You can use the Dial, DialWithTimeout or NewConn function to create a connection. When the task is completed, the application must call the Close function to complete the operation. .
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() }
Use
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) } }
Set key expiration time
_, err = conn.Do("expire", "name", 10) //10秒过期 if err != nil { fmt.Println("set expire error: ", err) return }
Get mget in batches and set mset in batches
_, 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 operation
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 Operation
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
Pipelining(Pipelining)
By using the three methods Send(), Flush() and Receive(), pipeline operations can be performed in a concurrent manner. The client can use the send() method to send one or more commands to the server at once. When the command is sent, the flush() method is used to send the command input in the buffer to the server at once. The client then uses the Receive() method in sequence. Read all command operation results in first-in, first-out order.
Send(commandName string, args ...interface{}) error Flush() error Receive() (reply interface{}, err error)
Send: Send the command to the buffer
Flush: Clear the buffer and send the command to the server in one go
Recevie: Read the server response results in sequence. When the read command does not respond, the operation will block.
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 publishing subscription mode
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
Transaction operation
MULTI, EXEC, DISCARD and WATCH are the basis of Redis transactions. Of course we use Go language essentially uses these commands when performing transaction operations on redis.
MULTI: Open transaction
EXEC: Execute transaction
DISCARD: Cancel transaction
WATCH: Monitor key changes in the transaction and cancel once there is a change affairs.
Example:
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]
Universal operation
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) }
All codes
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) } }
The above is the detailed content of How to operate redis and redigo in Go. For more information, please follow other related articles on the PHP Chinese website!

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

Redis's core functions include memory storage and persistence mechanisms. 1) Memory storage provides extremely fast read and write speeds, suitable for high-performance applications. 2) Persistence ensures that data is not lost through RDB and AOF, and the choice is based on application needs.

Redis'sServer-SideOperationsofferFunctionsandTriggersforexecutingcomplexoperationsontheserver.1)FunctionsallowcustomoperationsinLua,JavaScript,orRedis'sscriptinglanguage,enhancingscalabilityandmaintenance.2)Triggersenableautomaticfunctionexecutionone

Redisisbothadatabaseandaserver.1)Asadatabase,itusesin-memorystorageforfastaccess,idealforreal-timeapplicationsandcaching.2)Asaserver,itsupportspub/submessagingandLuascriptingforreal-timecommunicationandserver-sideoperations.

Redis is a NoSQL database that provides high performance and flexibility. 1) Store data through key-value pairs, suitable for processing large-scale data and high concurrency. 2) Memory storage and single-threaded models ensure fast read and write and atomicity. 3) Use RDB and AOF mechanisms to persist data, supporting high availability and scale-out.

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Chinese version
Chinese version, very easy to use
