https://pkg.go.dev/github.com/go-redis/redis
https://github.com/cheerego/go-redisson 分布式锁
github.com/go-redis/redis
c := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
//pong, err := c.Ping().Result() 用于测试
c.Do("set" ,"ids","11") //通用
s,_:=c.Do("get","ids").String()
c.Set("id",90,0)
s1:=c.Get("id").Val() //取值
c.RPush("ok","ni","ooo") 队列写入
s2:=c.BLPop(0,"ok").Val()队列取出
fmt.Println(s2)
s3:=c.Incr("qq").Val() 自动加一
fmt.Println(s3)
s4:=c.Subscribe("ch1") 订阅
defer s4.Close()
s4.Receive()
ch:=s4.Channel()
c.Publish("ch1","ok") 发布
for msg := range ch {
fmt.Println(msg.Channel, msg.Payload)
}
s5:=c.XRead(&redis.XReadArgs{
Streams: []string{"quee", "0"},
Count: 1,
Block: 100 * time.Millisecond,
}).Val()
//[{quee [{1637435746065-0 map[msg:中国 user:李白]}]}]
fmt.Println(s5[0].Messages[0].Values["msg"])
v,_:=c.Do("redisql.query", "db","select * from foo").Result()
for _, d := range v.([]interface{}) {
fmt.Println(d.([]interface{}))
y:=d.([]interface{})
fmt.Println(y[0],y[1],y[2])
}
id, _ := c.XAdd(&redis.XAddArgs{
Stream: "st:st",
ID: "*",
Values: map[string]interface{}{"dos": "deux"},
}).Result()
fmt.Println(id)
n, _ := c.XTrim("st:st", 10).Result()
fmt.Println(n)
nn, _ := c.XRange("st:st", "-", "+").Result()
fmt.Println(nn[0].Values["dos"])
c.XDel("st:st", "1-0").Result()
n, _ = c.XLen("st:st").Result()
fmt.Println(n)
nn, _ = c.XRangeN("st:st", "-", "+",2).Result()
fmt.Println(nn)
nn, _ = c.XRevRange("st:st", "+", "-").Result()
fmt.Println(nn)
res, _ := c.XReadStreams("st:st", "0").Result()
fmt.Println(res)
res1, _ := c.XRead(&redis.XReadArgs{
Streams: []string{"st:st", "0"},
Count: 2,
Block: 0,
}).Result()
fmt.Println(res1)
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/util/gconv"
conn := g.Redis().Conn()
defer conn.Close()
v1, _ := conn.Do("redisql.exec", "db","select * from foo")
for _, d := range gconv.Interfaces(v1) {
fmt.Println(d)
x:=gconv.Strings(d)
fmt.Println(x[0],x[1],x[2])
}
conn.Do("set","ids","你好") 用于设置
v, _ := conn.DoVar("GET", "ids") 用于获取方便转换数据
fmt.Println(v.String())
conn.Do("SUBSCRIBE", "ch1") //订阅发布
for {
reply, err := conn.ReceiveVar()
if err != nil {
panic(err)
}
fmt.Println(reply.Slice()[2])
}
conn.Do("hset","v","user","李白")
conn.Do("hset","v","sex","男")
v,_=conn.DoVar("hgetall","v")
fmt.Println(v.Map()["sex"])
"github.com/julienschmidt/httprouter" //常用路由
func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
user, password, hasAuth := r.BasicAuth()
if hasAuth && user == requiredUser && password == requiredPassword {
h(w, r, ps)
} else {
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
}
}
}
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "权限验证成功!\n")
}
func Hello(w http.ResponseWriter,r *http.Request, rx httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", rx.ByName("name"))
}
func main() {
r := httprouter.New()
r.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {//cors
if r.Header.Get("Access-Control-Request-Method") != "" {
header := w.Header()
header.Set("Access-Control-Allow-Methods", header.Get("Allow"))
header.Set("Access-Control-Allow-Origin", "*")
}
w.WriteHeader(http.StatusNoContent)
})
r.GET("/", BasicAuth(Index, "admin", "123456"))
r.GET("/hello/:name", Hello)
r.ServeFiles("/public/*filepath", http.Dir("public"))//静态文件服务器
r.NotFound=http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "没有找到这个文件")
})
log.Fatal(http.ListenAndServe(":8000", r))
import (
"fmt"
"github.com/fasthttp/router"
"github.com/valyala/fasthttp"
)
func BasicAuth(h fasthttp.RequestHandler, user []byte, passwd []byte) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
auths := ctx.Request.Header.Peek("Authorization")
auth := string(auths)
prefix := "Basic "
if strings.HasPrefix(auth, prefix) {
payload, err := base64.StdEncoding.DecodeString(
auth[len(prefix):],
)
if err == nil {
pair := bytes.SplitN(payload, []byte(":"), 2)
if len(pair) == 2 && bytes.Equal(pair[0], user) &&
bytes.Equal(pair[1], passwd) {
h(ctx)
return
}
}
}
ctx.Error(fasthttp.StatusMessage(fasthttp.StatusUnauthorized), fasthttp.StatusUnauthorized)
ctx.Response.Header.Set("WWW-Authenticate", "Basic realm=Restricted")
}
}
func Index(ctx *fasthttp.RequestCtx) {
ok:=ctx.QueryArgs().Peek("id")
fmt.Fprintf(ctx, "测试工具%s",string(ok))
}
func Hello(ctx *fasthttp.RequestCtx) {
fmt.Fprintf(ctx, "hello, %s !\n", ctx.UserValue("name"))
}
func main() {
r := router.New()
r.GET("/", BasicAuth(Index, []byte("admin"), []byte("123456")))
r.GET("/hello/{name}", Hello)
r.ServeFiles("/public/{filepath:*}", "./public")//静态文件服务器
fasthttp.ListenAndServe(":8000", r.Handler)
}
"github.com/bwmarrin/snowflake" //19位数字id
node, _ := snowflake.NewNode(1)
id := node.Generate()
fmt.Println(id.Int64())
"github.com/sony/sonyflake"
s:=sonyflake.NewSonyflake(sonyflake.Settings{})
id,_:=s.NextID() //uint64
idgen github.com/yitter/idgenerator-go 15位
var options = idgen.NewIdGeneratorOptions(1)
idgen.SetIdGenerator(options) //全局初始化
var newId = idgen.NextId()
https://github.com/alicebob/miniredis 用于测试redis
s, _ := miniredis.Run()
defer s.Close()
s.Set("id", "1") //设置key
n,_:=s.Incr("id",1) //自动+1,可设定值 Incrfloat
s1,_:=s.Get("id") //获取key
s.Host() //127.0.0.1
s.Port() //端口
s.Addr() //127.0.0.1:23456
s1:=s.Keys() //获取全部key
s1:=s.Type("id") 判断类型
s.HSet("id","name","李白")
s1:=s.HGet("id","name")
s.HIncr("id","name",2) HIncrfloat
s.HDel("id","name")
s1,_:=s.HKeys("id") 获取key [name]
s.Lpush("ls","1") 左边增加元素
s1,_:=s.List("ls") [1] 返回list集合
s2,_:=s.Lpop("ls") 左边删除 并返回这个元素
s.Push("ls","5","7") //追加增加元素
s2,_:=s.Pop("ls") 右边删除返回元素
github.com/gomodule/redigo/redis //不支持Streams
c, err := redis.Dial("tcp", "127.0.0.1:6379")
if err != nil {
panic(err)
}
defer c.Close()
c.Do("set", "foo", 1)
n,_:=redis.String(c.Do("get", "foo"))
fmt.Println(n)
c.Send("set","ab","vsgo")//发送到缓存
c.Send("get","ab")
c.Send("set","abc","123")
c.Send("get","abc")
c.Flush()//执行
c.Receive()//1 返回结果
c.Receive()//2
c.Receive()//3
v,_:=c.Receive()//4
fmt.Println(string(v.([]uint8)))
d:=redis.PubSubConn{Conn: c} //发布订阅
d.Subscribe("ch1")
c.Do("publish","ch1","vsv中")
for {
switch v := d.Receive().(type) {
case redis.Message:
fmt.Println(string(v.Data)) //输出
case redis.Subscription:
fmt.Println(v.Count)
case error:
return
}
}
文档更新时间: 2022-11-10 12:02 作者:Yoby