当前位置: 首页 > linux, redis > 正文

golang 环境上搭建 redis 客户端(gosexy)及安装 mysql 驱动

本文会继续之前的任务,在 golang 上搭建 redis client 环境和安装测试 mysql 驱动(driver),确保go可以正确连上 redis 和 mysql 。环境仍然是CentOS-6.x x86-64bit。
由于我们可怜的开发同学,在windows下整了一周仍然没有把环境弄利索,无奈之下,只有老夫亲自出马。

golang 环境的搭建可以参考之前的文章:CentOS-6.x下搭建golang环境的三种方式

redis 安装过程

yum install tcl
http://redis.io/
http://download.redis.io/releases/redis-2.8.6.tar.gz
tar zxvf redis-2.8.6.tar.gz
cd redis-2.8.6
make
make test
make install

redis配置文件-片段:

cat /etc/redis.conf
daemonize yes
pidfile /var/run/redis.pid
port 6379
bind 192.168.200.111

启动redis

/usr/local/bin/redis-server /etc/redis.conf

go for redis有众多的redis client,http://redis.io/上面可以任意选一个吧,我这选择了gosexy/redis

安装redis client

go get -u menteslibres.net/gosexy/redis

安装过程有这样两个小问题:
#package menteslibres.net/gosexy/redis: cannot download, $GOPATH not set. For more details see: go help gopath
#package menteslibres.net/gosexy/redis: cannot download, $GOPATH must not be set to $GOROOT. For more details see: go help gopath

解决办法,需要配置GOPATH:

vi /etc/profile
add
export GOPATH=/home/sudops.com/go

source /etc/profile

可以查看下 golang 关于GOPATH的说明:

#go help gopath
Here's an example directory layout:

    GOPATH=/home/user/gocode

    /home/user/gocode/
        src/
            foo/
                bar/               (go code in package bar)
                    x.go
                quux/              (go code in package main)
                    y.go
        bin/
            quux                   (installed command)
        pkg/
            linux_amd64/
                foo/
                    bar.a          (installed package object)

golang 连接redis测试案例:

cat connredis.go

package main

import (
	"menteslibres.net/gosexy/redis"
	"log"
)

var host = "192.168.200.111"
var port = uint(6379)

var client *redis.Client

func main() {
	var s string
	var err error

	client = redis.New()

	err = client.Connect(host, port)

	if err != nil {
		log.Fatalf("Connect failed: %s\n", err.Error())
		return
	}

	log.Println("Connected to redis-server.")

	// DEL hello
	log.Printf("DEL hello\n")
	client.Del("hello")

	// SET hello 1
	log.Printf("SET hello 1\n")
	client.Set("hello", 1)

	// INCR hello
	log.Printf("INCR hello\n")
	client.Incr("hello")

	// GET hello
	log.Printf("GET hello\n")
	s, err = client.Get("hello")

	if err != nil {
		log.Fatalf("Could not GET: %s\n", err.Error())
		return
	}

	log.Printf("> hello = %s\n", s)

	client.Quit()
}

golang connect redis 执行结果:

go run connredis.go 
2014/02/26 14:01:01 Connected to redis-server.
2014/02/26 14:01:01 DEL hello
2014/02/26 14:01:01 SET hello 1
2014/02/26 14:01:01 INCR hello
2014/02/26 14:01:01 GET hello
2014/02/26 14:01:01 > hello = 2

安装mysql

yum install mysql mysql-server mysql-devel mysql-libs

golang 的mysql 驱动
驱动地址:https://github.com/go-sql-driver/mysql
安装

go get github.com/go-sql-driver/mysql

创建数据库及测试数据:

create database shortlink;

grant all privileges on mydb.* to sudops@'%' identified by 'mypasswd';
flush privileges;

use mydb;
create table squareNum (number int(11) PRIMARY KEY,squareNumber int(11) not null);

desc squareNum;
+--------------+---------+------+-----+---------+-------+
| Field        | Type    | Null | Key | Default | Extra |
+--------------+---------+------+-----+---------+-------+
| number       | int(11) | NO   | PRI | NULL    |       |
| squareNumber | int(11) | NO   |     | NULL    |       |
+--------------+---------+------+-----+---------+-------+

go 连接mysql的完整例子:

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	db, err := sql.Open("mysql", "sudops:mypasswd@tcp(192.168.200.111:3306)/mydb")
	if err != nil {
		panic(err.Error())  // Just for example purpose. You should use proper error handling instead of panic
	}
	defer db.Close()

	// Prepare statement for inserting data
	stmtIns, err := db.Prepare("INSERT INTO squareNum VALUES( ?, ? )") // ? = placeholder
	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}
	defer stmtIns.Close() // Close the statement when we leave main() / the program terminates

	// Prepare statement for reading data
	stmtOut, err := db.Prepare("SELECT squareNumber FROM squarenum WHERE number = ?")
	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}
	defer stmtOut.Close()

	// Insert square numbers for 0-24 in the database
	for i := 0; i < 25; i++ {
		_, err = stmtIns.Exec(i, (i * i)) // Insert tuples (i, i^2)
		if err != nil {
			panic(err.Error()) // proper error handling instead of panic in your app
		}
	}

	var squareNum int // we "scan" the result in here

	// Query the square-number of 13
	err = stmtOut.QueryRow(13).Scan(&squareNum) // WHERE number = 13
	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}
	fmt.Printf("The square number of 13 is: %d", squareNum)

	// Query another number.. 1 maybe?
	err = stmtOut.QueryRow(1).Scan(&squareNum) // WHERE number = 1
	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}
	fmt.Printf("The square number of 1 is: %d", squareNum)
}

测试结果:

go run connmysql.go 
The square number of 13 is: 169 
The square number of 1 is: 1

Erveryting goes perfect,一切看上去非常美好,golang 环境上搭建redis client和mysql驱动都已经配置完毕,golang 连接redis和mysql的环境都准备好啦,开发终于可以正式开始了,还等什么?

本文固定链接: https://sudops.com/golang-redis-client-and-mysql-driver.html | 运维速度

该日志由 u2 于2014年02月26日发表在 linux, redis 分类下,
原创文章转载请注明: golang 环境上搭建 redis 客户端(gosexy)及安装 mysql 驱动 | 运维速度
关键字: , ,

golang 环境上搭建 redis 客户端(gosexy)及安装 mysql 驱动:目前有1 条留言