从零开始写数据库(三)

创建具有网络功能的数据库

修改main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main

import (
"fmt"
"net"
"bufio"
"os"
"strings"
)

func main() {
defer Save()

// 监听8080端口
ln, err := net.Listen("tcp", ":8080")
if err != nil {
// handle error
}
// 死循环
for {
// 拿到连接
conn, err := ln.Accept()
if err != nil {
// handle error
continue
}
// 处理函数
go handleConnection(conn)
}


}

func handleConnection(conn net.Conn) {

// Response,返回数据
send := bufio.NewWriter(conn)

// Request,接受数据
scanner := bufio.NewScanner(conn)

// 这里以\n作为分隔符
for scanner.Scan() {
// 命令分隔符,这里以一个空格作为分隔符
arr := strings.Split(scanner.Text(), " ")

command := arr[0]

fmt.Println(command)


switch command {
case "set":
key, value := arr[1], arr[2]
Put(key, value)
send.WriteString("Set success!\n")
case "get":
key := arr[1]

value := Get(key)

if value == "" {
send.WriteString("Get fail, key not found!\n")
} else {
send.WriteString("Get success, this is result: ")
send.WriteString(value)
send.WriteString("\n")
}

case "del":
key := arr[1]
Delete(key)
send.WriteString("Del success!\n")
default:
fmt.Println("Not support command!")
}

send.Flush()
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
}

这里用类似redis的command处理请求

  1. 新增、修改

    1
    set [key] [value]
  2. 读取

    1
    get [key]
  3. 删除

    1
    del [key]

我们使用telnet来测试

1
2
3
4
5
6
7
8
9
10
11
12
13
telnet 127.0.0.1 8080

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
set a b
Set success!
get a
Get success, this is result: b
del a
Del success!
get a
Get fail, key not found!

如预期的一致,这个时候我们的数据具有了处理网络连接的功能,但是显然这样的数据库还是太弱了。我们的最终目标是创建一个类似LevelDB+Redis的数据库