golang总结-Redis整合

Posted hu1056043921

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang总结-Redis整合相关的知识,希望对你有一定的参考价值。

go get github.com/gomodule/redigo/redis

1. 基本用法

  1. 获取连接
package conn

import (
    "github.com/gomodule/redigo/redis"
    "log"
)

const (
    redis_passwd = ""
    redis_host = ""
    redis_port = ""
    redis_address = "192.168.2.130:6379"
)

func getConn() redis.Conn {
    conn, err := redis.Dial("tcp", redis_address)
    if err != nil {
        log.Println("redis connect err", err)
        panic(err)
    }
    return conn
}
  1. 操作redis
package conn

import (
    "fmt"
    "github.com/gomodule/redigo/redis"
    "log"
)

var c = getConn()

//string 操作

func Set(key string, value interface{}) bool {
    defer c.Close()
    _, err := c.Do("set", key, value)
    if err != nil {
        log.Println("set a value error,", err)
        return false
    }
    return true
}


func Get(key string) string {
    defer c.Close()
    value, err := redis.String(c.Do("get", key))
    if err != nil {
        log.Println("get a value error,", err)
        return ""
    }

    return value
}

func Del(key string) bool {
    defer c.Close()
    _, err := c.Do("del", key)
    if err != nil {
        log.Println("del a key error, ", err)
        return false
    }
    return true
}

//Hash操作
func HashSet(key string, data map[string]interface{}) {
    defer c.Close()
    for k, v := range data {
        _, err := c.Do("hset", key, k, v)
        if err != nil {
            log.Println("hset a error, ", err)
            continue
        }
    }
}

func HashMGet(key string) map[string]interface{} {
    defer c.Close()

    data := make(map[string]interface{})

    reply, err := redis.ByteSlices(c.Do("hgetall", key))
    if err != nil {
        log.Println("hmget error, ", err)
        return nil
    }
    for i, v := range reply {
        fmt.Println(string(v))
        if i % 2 == 0 {
            data[string(v)] = string(reply[i+1])
        }
        continue
    }
    return data

}

2. Redis连接池

package pool

import (
    "github.com/gomodule/redigo/redis"
    "time"
)

var (
    pool *redis.Pool
)

const (
    redis_host = "192.168.2.130:6379"
)

func init() {
    pool = &redis.Pool{
        MaxIdle: 10,
        MaxActive: 0, //0表示没有限制
        IdleTimeout: 1 * time.Second,
        Dial: func() (redis.Conn, error) {
            return redis.Dial("tcp", redis_host)
        },
    }
}

获取连接:conn := pool.Get()

以上是关于golang总结-Redis整合的主要内容,如果未能解决你的问题,请参考以下文章

golang goroutine例子[golang并发代码片段]

golang代码片段(摘抄)

Redis整合spring总结

spring boot 整合 redis

全栈编程系列SpringBoot整合Shiro(含KickoutSessionControlFilter并发在线人数控制以及不生效问题配置启动异常No SecurityManager...)(代码片段

代码片段 - Golang 实现简单的 Web 服务器