Go语言操作redis数据库

1、测试Go语言如何操作Redis数据库
2、网络请求redis中存储的图片,并返回
在这里插入图片描述
涉及到的redisgo库:https://download.csdn.net/download/xwb_12340/12411912

import (
	"net/http"
	"net/url"
	"github.com/garyburd/redigo/redis"
)
func RedisTest(w http.ResponseWriter,r *http.Request){
	connect, err := redis.Dial("tcp", "127.0.0.1:6379")
	if err != nil{
		fmt.Println(err)
	}
	defer connect.Close()
	//写入字符串
	_,err = connect.Do("SET","Name","xuweibao")
	if err!=nil{
		fmt.Println("set value failde:",err)
	}
	//检查key值是否存在,如果存在,exits=1,否则exits=0
	exits,err := connect.Do("EXISTS","Name")
	//转换为bool类型
	exits,err = redis.Bool(exits,err)
	if err!=nil{
		fmt.Println("set value failde:",exits)
	}
	if exits==true{
		//获取字符串数据
		name,err := redis.String(connect.Do("GET","Name"))
		if err==nil{
			fmt.Println("Name:",name)
		}

	}
	//写入hash值,即结构体
	var p1, p2 struct {
		Title  string `redis:"title"`
		Author string `redis:"author"`
		Body   string `redis:"body"`
	}

	p1.Title = "Example"
	p1.Author = "Gary"
	p1.Body = "Hello"
	//使用HMSET设置值
	if _, err := connect.Do("HMSET", redis.Args{}.Add("id1").AddFlat(&p1)...); err != nil {
		fmt.Println(err)
		return
	}

	m := map[string]string{
		"title":  "Example2",
		"author": "Steve",
		"body":   "Map",
	}

	if _, err := connect.Do("HMSET", redis.Args{}.Add("id2").AddFlat(m)...); err != nil {
		fmt.Println(err)
		return
	}
	//从数据库中读取结构体数据
	for _, id := range []string{"id1", "id2"} {

		v, err := redis.Values(connect.Do("HGETALL", id))
		if err != nil {
			fmt.Println(err)
			return
		}

		if err := redis.ScanStruct(v, &p2); err != nil {
			fmt.Println(err)
			return
		}

		fmt.Printf("%+v\n", p2)
	}

	//写入图片
	var tile1	GetTileResponse
	tile,err :=ioutil.ReadFile("tile.jpg")
	if err==nil{
		tile1.data = tile
		//写入数据库
		_, err := connect.Do("HMSET", "tile1","tileId2",tile)
		if  err != nil {
			fmt.Println(err)
			return
		}

	}
	//获取图片
	img,err:=redis.Bytes(connect.Do("HGET","tile1","tileId2"))
	if err==nil{
		w.Write(img)
	}
	}

猜你喜欢

转载自blog.csdn.net/xwb_12340/article/details/106075870