go language study notes 5 (network programming, Redis)

go network programming

Server-side server.go

import "net"
// 为每一个客户端请求开启协程
func process(conn net.Conn) {
	defer conn.Close()    //关闭连接
	for {
		buf := make([]byte, 1024)
		//等待读取conn里的client消息,如果没收到消息会阻塞,n代表读到的字节数
		n,err := conn.Read(buf)
		// 将收到的client信息打印,注意1:必须是Print因为从client读取时已带换行换行,真正读取的数据到n为止
		fmt.Print(string(buf[:n]))
	}
}

func main() {
	// 服务器监听8000端口
	listen, err = net.Listen("tcp", 0.0.0.0:8000)
	
	defer listen.Close()
	
	// 等待客户端连接
	for {
		conn, err = listen.Accept()
		
		// 得到客户端的ip和port
		ip_port := conn.RemoteAddr().string
		go process(conn)
	}
}

Client client.go

import "net"
import "bufio"

func main() {
	// server端的ip和port
	conn, err = net.Dial("tcp", 192.168.1.10:8888)

	// 客户端发送数据到服务器
	// ①:client先从终端获取标准输入
	reader,err := bufio.NewReader(os.Stdin)
	line,err := reader.ReadString('\n')  // 以换行作为终止标志
	
	// ②:将读取的数据发给server,参数是byte类型的切片,返回的是字符串
	n,err := conn.Write([]byte(line))
	fmt.Printf("发送给server的数据:%v", n)
}

Redis

  • The default port 6379

  • Switching database: select 1

  • Adding data: set name amber added to the database by default 0

  • Clear the current database: flushdb

  • Clear all databases: flushall

  • Delete a set of data: del name

  • Simultaneously setting a plurality of values: mset name amber age 10

  • At the same time get more value: mget name age

  • Hash assignment to the object: hset user1 name amber

  • Gets the object hash value: hget user1 "name"

  • Hash once obtain all the information: hgetall user1

  • Hash assignment all at once: hmset user2 name "lucy" age 44 job "java"

  • Hash fetching more: hmget user2 name age

  • Hash view object set several attributes: hlen user2

  • Check whether the hash object has the specified field: hexist user name

Redis List: a key value may correspond to a plurality of

  • Insert List (left): hpush num 1 2 3
  • List insert (right): rpush num 1 2 3
  • List Gets All: lrange 0 -1
  • List pop-up (far left): lpop num
  • List pop-up (far right): rpop num
  • Delete List: del num
  • List Length: llen num

Redis Set: disordered

  • Insert: sadd name amber bella mike
  • Additionally inserted: sadd name mike prompted to add fail
  • View: smembers name
  • Check whether the specified key data exists in: sismember name mike
  • Remove the specified data bella: srem name bella

go Redis connection

import "github.com/xxx/redis"

func main() {
	// go连接redis
	conn,er := redis.Dial("tcp", "192.168.1.10:6379")
	defer conn.Close()
	
	// 向redis写入数据,返回值是空接口类型,set首字母大小写随意
	_,err = conn.Do("set", "name", "amber")
	
	// res对应的是空接口类型,需要类型转换
	res,err := redis.String(conn.Do("get", "name"))

// 上述的set/get均可更换成hset/hget等方式
}

Redis connection pool
definition: create multiple connection pool conn, not closed, each available directly from the connection pool when the client requests a connection, while reducing consumption of resources due to the closure

import "github.com/xxx/redis"

var pool *redis.Pool   //定义全局pool
// 程序启动时初始化连接池
func init() {
	pool = &redis.Pool{
		MaxIdle : 8,    //最大空闲数
		MaxActice : 0,  //最大连接数,0代表不限制
		IdleTimeout : 100,   //中断连接超过100s,放回连接池
		Dial : func() (redis.Conn{}, err){
			return redis.Dial("tcp", "192.168.1.10:6379")   //初始化连接,指定主机
		}
	}
}

func main() {
	// 从pool取出连接
	conn := pool.Get()
	defer conn.Close()
	_, err := conn.Do("set", "name", "amber")
	r, err := redis.String(conn.Do("get", "name"))
	fmt.Println("name=", r)
}
// pool要始终保持开启,不可关闭
发布了171 篇原创文章 · 获赞 72 · 访问量 8853

Guess you like

Origin blog.csdn.net/ambzheng/article/details/103646350