This is the 24th day of my participation in the August More Text Challenge

Introduction to the

Redis is an open source key/value database that uses memory to cache data

Redis provides data structures such as strings, lists, collections, hashes, and more

Redis has the advantage of high performance, up to 110,000 reads per second, up to 80,000 writes per second, rich data types, and non-rich features such as subscription publishing, notifications, key expiration, etc

Application scenarios

  • Caching systems reduce the pressure on relational data
  • Counting the number of followers, the number of fans
  • Leaderboards Various ranking lists

The installation

Install the docker

To save time, write the code directly, here is based on Docker to quickly install Redis, portal: juejin.cn/post/684490…

docker run --name redis -p 6379:6379 -d redis:5.07.
Copy the code

Installing the UI Tool

If RedisDesktopManager is not installed on the local PC, you can also install the Web UI tool as follows

mkdir -p ./p3x-redis-ui-settings
docker run -v $PWD/p3x-redis-ui-settings:/settings -h docker-p3x-redis-ui -p 7843:7843 -t -i -d patrikx3/p3x-redis-ui
Copy the code

The client

At present, there are two popular clients on Github, both of which have more than 8K stars, but they have features to describe the different functions

Github.com/go-redis/re… The performance is as follows:

  • Redis 3 commands except QUIT, MONITOR, and SYNC.
  • Automatic connection pooling with circuit breaker support.
  • Pub/Sub.
  • Transactions.
  • Pipeline and TxPipeline.
  • Scripting.
  • Timeouts.
  • Redis Sentinel.
  • Redis Cluster.
  • Cluster of Redis Servers without using cluster mode and Redis Sentinel.
  • Ring.
  • Instrumentation.

Github.com/gomodule/re… The performance is as follows:

  • A Print-like API with support for all Redis commands.
  • Pipelining, including pipelined transactions.
  • Publish/Subscribe.
  • Connection pooling.
  • Script helper type with optimistic use of EVALSHA.
  • Helper functions for working with command replies.

Go-redis is used for writing services, and gomodule is used for command line tools

API example

Here, the Go-Redis client is used to test relevant API functions with a single Redis instance

Initialize the

Define global variables for client, CTX,err. Functions are often used to check the connection status at the start of the project, and then focus on the business code

var (
   ctx = context.Background()
   rdb *redis.Client
   err error
)

func init() {
   / / connect to redis
   rdb = redis.NewClient(&redis.Options{Addr: "ip:6379".Password: "".DB: 0})
   // Health check
   _, err = rdb.Ping(ctx).Result()
   iferr ! = nil { log.Fatalln("Redis status error:",err)
   }
}
Copy the code

String type

String data type, each key corresponds to a value.. Simple to operate. There is also an expiration time setting, 0 means no expiration

func stringKV() {
   / / new k/v
   _ = rdb.Set(ctx, "hello"."world".0).Err()

   //获取k/v
   result, _ := rdb.Get(ctx, "hello").Result()
   fmt.Println(result)

   / / delete
   _, _ = rdb.Del(ctx, "hello").Result()

}
Copy the code

List the type

A list is a simple list of strings, sorted by insertion order. You can add an element to either the head (left) or the tail (right) of the list

The following code shows general operations such as CURD

func listKV() {
   / / new
   _ = rdb.RPush(ctx, "list"."message").Err()
   _ = rdb.RPush(ctx, "list"."message2").Err()

   / / query
   result, _ := rdb.LLen(ctx, "list").Result()
   fmt.Println(result)

   / / update
   _ = rdb.LSet(ctx, "list".2."message set").Err()

   / / traverse
   lRange,_ := rdb.LRange(ctx, "list".0, result).Result()
   for _,v := range lRange {
      log.Println(v)
   }
   

   / / delete
   _, _ = rdb.LRem(ctx, "list".3."message2").Result()
}
Copy the code

Hash type

A hash is a mapping of fields and values of string type. Hash is especially useful for storing objects

func hashKV() {
   data := map[string]interface{}{
      "name":"Zhang"."age": 66,}/ / new
   _ = rdb.HMSet(ctx, "hash", data).Err()

   / / query
   result, _ := rdb.HMGet(ctx, "hash"."name").Result()
   fmt.Println(result)

   / / all
   m, _ := rdb.HGetAll(ctx, "hash").Result()
   fmt.Println("m: ",m)

   // Check whether the value exists
   b, _ := rdb.HExists(ctx, "hash"."age").Result()
   fmt.Println("b: ",b)

   / / delete
   _, _ = rdb.HDel(ctx, "hash").Result()
}
Copy the code

Collection types

A Set is an unordered collection of type String. Collection members are unique, which means that no duplicate data can occur in the collection.

The encoding of a collection object can be intSet or HashTable.

The collection in Redis is realized by hash table, so the complexity of adding, deleting and searching is O(1).

func setKV() {
   / / new
   result, _ := rdb.SAdd(ctx, "set"."aa"."bb"."cc"."dd"."ee").Result()
   fmt.Println(result)

   // Count
   i, _ := rdb.SCard(ctx, "set").Result()
   fmt.Println(i)

   // Member information
   i2, _ := rdb.SMembers(ctx, "set").Result()
   fmt.Println(i2)

   / / delete
   _, _ = rdb.SRem(ctx, "set"."cc").Result()
}
Copy the code

Ordered set type

Ordered collections, like collections, are collections of string elements and do not allow duplicate members.

The difference is that each element is associated with a double score. Redis uses scores to sort the members of a collection from smallest to largest. The members of an ordered set are unique, but the score can be repeated

func sortSetKV() {
   / / new
   for i:=1; i<100; i++ {data := redis.Z{
         Score:  float64(i),
         Member: i,
      }
      _, _ = rdb.ZAdd(ctx, "sortSet", &data).Result()
   }

   / / statistics
   result, _ := rdb.ZCard(ctx, "sortSet").Result()
   fmt.Println(result)

   / / query
   result2, _ := rdb.ZRange(ctx, "sortSet".0, result).Result()
   fmt.Println(result2)
}
Copy the code

Release subscription

Publish subscription (PUB/SUB) is a message communication pattern: the sender (PUB) sends the message and the subscriber (sub) receives the message. The Redis client can subscribe to any number of channels

func pubsub() {
   subscribe := rdb.Subscribe(ctx,"sub1")
   _, _ = subscribe.Receive(ctx)
   channel := subscribe.Channel()
   
   _ = rdb.Publish(ctx, "sub1"."message1").Err()
   _ = rdb.Publish(ctx, "sub1"."message2").Err()
   for msg := range channel {
      log.Println(msg.Channel,msg.Payload)
   }
}
Copy the code