go使用redis消息队列

go使用redis消息队列

import "github.com/gomodule/redigo/redis"

var (
	RedisPools  *RedisPool
)

type Job struct {
	Class string        `json:"Class"`
	Args  string        `json:"Args"`
}

//redis连接池
type RedisPool struct {
	pool *redis.Pool
}

func NewRedisPool() {
	server :=  “127.0.0.1:6379”
	password := “123456”
	pool := &redis.Pool{
		MaxIdle:     3,                    //最大空闲连接数
		IdleTimeout: 240 * time.Second,    //最大空闲连接时间
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", server)
			if err != nil {
				return nil, err
			}
			if password != "" {
				if _, err := c.Do("AUTH", password); err != nil {
					c.Close()
					return nil, err
				}
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
	RedisPools = &RedisPool{pool}
}

#获取队列内容 队列名key
func (r *RedisPool) GetJob(key string) (*Job, error) {
	c := r.pool.Get()
	defer c.Close()

	reply, err := c.Do("LPOP", key)
	if err != nil || reply == nil {
		if err != nil {
			fmt.Println("GetJob error:", err)
		}
		return nil, errors.New("no Job.")
	}
	var j Job
	decoder := json.NewDecoder(bytes.NewReader(reply.([]byte)))
	if err := decoder.Decode(&j); err != nil {
		fmt.Println("GetJob error:", err)
		return nil, err
	}
	return &j, nil
}

#将消息放进消息队列
func (r *RedisPool) PutJob(job *Job, key string) error {
	c := r.pool.Get()
	defer c.Close()
	b, err := json.Marshal(job)
	if err != nil {
		fmt.Println("PutJob error:", job.Args, err)
		return err
	}
	_, err = c.Do("rpush", key, b)
	if err != nil {
		fmt.Println("PutJob error:", job.Args, err)
		return err
	}
	return nil
}

func main(){
	pool:= RedisPools  
	//发送job到队列
   pool.PutJob(job,"queue")
   //接收消息
	data,_ := pool.GetJob("queue")
}

你可能感兴趣的:(golang学习之路)