├── doc ├── 15559831930272.jpg ├── 15560015987025.jpg ├── 15560016291736.jpg ├── 15560017023669.jpg ├── 15560018447765.jpg ├── 15560059511302.jpg ├── 15560059607703.jpg ├── 15560094190704.jpg ├── 15560094299023.jpg ├── 15560094387666.jpg ├── 15560126952552.jpg ├── 15560726975250.jpg ├── 15560729656703.jpg ├── 15560730272299.jpg ├── 15560774419983.jpg ├── 15560776646355.jpg ├── 15560849239804.jpg ├── 15560900273343.jpg ├── 15560923838579.jpg ├── 15560924007549.jpg ├── 15560925944012.jpg ├── 15560929305585.jpg └── 15560975312422.jpg ├── common └── message.go ├── chatroom.go ├── .gitignore ├── v3 ├── client.go └── chatroom.go ├── v1 └── chatroom.go ├── auto_client └── auto_client.go ├── v2 └── chatroom.go ├── client.html ├── README.md └── LICENSE /doc/15559831930272.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15559831930272.jpg -------------------------------------------------------------------------------- /doc/15560015987025.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560015987025.jpg -------------------------------------------------------------------------------- /doc/15560016291736.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560016291736.jpg -------------------------------------------------------------------------------- /doc/15560017023669.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560017023669.jpg -------------------------------------------------------------------------------- /doc/15560018447765.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560018447765.jpg -------------------------------------------------------------------------------- /doc/15560059511302.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560059511302.jpg -------------------------------------------------------------------------------- /doc/15560059607703.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560059607703.jpg -------------------------------------------------------------------------------- /doc/15560094190704.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560094190704.jpg -------------------------------------------------------------------------------- /doc/15560094299023.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560094299023.jpg -------------------------------------------------------------------------------- /doc/15560094387666.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560094387666.jpg -------------------------------------------------------------------------------- /doc/15560126952552.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560126952552.jpg -------------------------------------------------------------------------------- /doc/15560726975250.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560726975250.jpg -------------------------------------------------------------------------------- /doc/15560729656703.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560729656703.jpg -------------------------------------------------------------------------------- /doc/15560730272299.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560730272299.jpg -------------------------------------------------------------------------------- /doc/15560774419983.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560774419983.jpg -------------------------------------------------------------------------------- /doc/15560776646355.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560776646355.jpg -------------------------------------------------------------------------------- /doc/15560849239804.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560849239804.jpg -------------------------------------------------------------------------------- /doc/15560900273343.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560900273343.jpg -------------------------------------------------------------------------------- /doc/15560923838579.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560923838579.jpg -------------------------------------------------------------------------------- /doc/15560924007549.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560924007549.jpg -------------------------------------------------------------------------------- /doc/15560925944012.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560925944012.jpg -------------------------------------------------------------------------------- /doc/15560929305585.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560929305585.jpg -------------------------------------------------------------------------------- /doc/15560975312422.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LinkinStars/simple-chatroom/HEAD/doc/15560975312422.jpg -------------------------------------------------------------------------------- /common/message.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | // 消息结构 4 | type Message struct { 5 | Token string `json:"token"` //token用于表示发起用户 6 | Content string `json:"content"` //content表示消息内容,这里简化别的消息 7 | } 8 | -------------------------------------------------------------------------------- /chatroom.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/LinkinStars/golang-util/gu" 5 | "github.com/LinkinStars/simple-chatroom/v3" 6 | _ "net/http/pprof" 7 | ) 8 | 9 | func main() { 10 | // 初始化日志(可以忽略,日志好看一些) 11 | gu.InitEasyZapDefault("simple-chatroom") 12 | // 启动! 13 | v3.StartChatRoom() 14 | } 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | ### IntelliJ IDEA ### 15 | .idea 16 | *.iws 17 | *.iml 18 | *.ipr 19 | 20 | ### logs ### 21 | logs -------------------------------------------------------------------------------- /v3/client.go: -------------------------------------------------------------------------------- 1 | package v3 2 | 3 | import ( 4 | "github.com/LinkinStars/simple-chatroom/common" 5 | "github.com/gorilla/websocket" 6 | "go.uber.org/zap" 7 | "time" 8 | ) 9 | 10 | // 客户端 11 | type Client struct { 12 | conn *websocket.Conn 13 | send chan common.Message 14 | } 15 | 16 | // 读取消息 17 | func (c *Client) ReadMessage() { 18 | preMessageTime := int64(0) 19 | for { 20 | // 接收消息 21 | message := &common.Message{} 22 | if err := c.conn.ReadJSON(message); err != nil { 23 | c.conn.Close() 24 | chatRoom.unregister <- c 25 | return 26 | } 27 | 28 | // 限制用户发送消息频率,每1秒只能发送一条消息 29 | curMessageTime := time.Now().Unix() 30 | if curMessageTime-preMessageTime < 0 { 31 | zap.S().Warn("1秒内无法再次发送") 32 | continue 33 | } 34 | preMessageTime = curMessageTime 35 | 36 | chatRoom.send <- *message 37 | } 38 | } 39 | 40 | // 发送消息 41 | func (c *Client) SendMessage() { 42 | for { 43 | m := <-c.send 44 | if err := c.conn.WriteJSON(m); err != nil { 45 | c.conn.Close() 46 | chatRoom.unregister <- c 47 | return 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /v1/chatroom.go: -------------------------------------------------------------------------------- 1 | package v1 2 | 3 | import ( 4 | "github.com/LinkinStars/simple-chatroom/common" 5 | "github.com/gorilla/websocket" 6 | "go.uber.org/zap" 7 | "net/http" 8 | ) 9 | 10 | var ( 11 | chatRoom *Room 12 | ug = websocket.Upgrader{ 13 | // 允许跨域 14 | CheckOrigin: func(r *http.Request) bool { 15 | return true 16 | }, 17 | } 18 | ) 19 | 20 | // 聊天室配置 21 | type Room struct { 22 | Connections []*websocket.Conn // 连接池,保存所有连接用户 23 | } 24 | 25 | // 处理所有websocket请求 26 | func chatRoomHandle(w http.ResponseWriter, r *http.Request) { 27 | log := zap.S() 28 | conn, err := ug.Upgrade(w, r, nil) 29 | if err != nil { 30 | log.Error(err) 31 | return 32 | } 33 | defer conn.Close() 34 | 35 | // 每次有连接进来就加入连接池 36 | chatRoom.Connections = append(chatRoom.Connections, conn) 37 | 38 | for { 39 | // 接收消息 40 | message := &common.Message{} 41 | if err := conn.ReadJSON(message); err != nil { 42 | log.Error(err) 43 | return 44 | } 45 | 46 | // 处理消息 47 | go chatRoom.batchSendMessage(*message) 48 | } 49 | } 50 | 51 | // 群发消息 52 | func (*Room) batchSendMessage(message common.Message) { 53 | log := zap.S() 54 | for i := 0; i < len(chatRoom.Connections); i++ { 55 | conn := chatRoom.Connections[i] 56 | if err := conn.WriteJSON(message); err != nil { 57 | log.Error("发送消息异常,移除连接") 58 | conn.Close() 59 | chatRoom.Connections = append(chatRoom.Connections[:i], chatRoom.Connections[i+1:]...) 60 | i-- 61 | } 62 | } 63 | } 64 | 65 | // 启动聊天室 66 | func StartChatRoom() { 67 | log := zap.S() 68 | log.Info("聊天室启动....") 69 | chatRoom = &Room{} 70 | http.HandleFunc("/chatroom", chatRoomHandle) 71 | http.ListenAndServe(":8081", nil) 72 | } 73 | -------------------------------------------------------------------------------- /auto_client/auto_client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/LinkinStars/simple-chatroom/common" 6 | "github.com/gorilla/websocket" 7 | "math/rand" 8 | "net/url" 9 | "strconv" 10 | "time" 11 | ) 12 | 13 | type Sender struct { 14 | conn *websocket.Conn 15 | send chan common.Message 16 | } 17 | 18 | func main() { 19 | clients := createClients(10) 20 | process(clients) 21 | } 22 | 23 | // 创建一定数量的客户端 24 | func createClients(amount int) []*Sender { 25 | var clients []*Sender 26 | u := url.URL{Scheme: "ws", Host: "127.0.0.1:8081", Path: "/chatroom"} 27 | for i := 0; i < amount; i++ { 28 | c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) 29 | if err != nil { 30 | panic(err) 31 | } 32 | sender := &Sender{ 33 | conn: c, 34 | send: make(chan common.Message, 128), 35 | } 36 | go sender.loopSendMessage() 37 | clients = append(clients, sender) 38 | } 39 | return clients 40 | } 41 | 42 | // 随机的选择一些用户去发送消息 43 | func process(clients []*Sender) { 44 | // 设置随机种子 45 | rand.Seed(time.Now().UnixNano()) 46 | 47 | clientsAmount := len(clients) - 1 48 | 49 | flag := 0 50 | for { 51 | time.Sleep(time.Millisecond * 1) 52 | go func() { 53 | randIndex := rand.Intn(clientsAmount) 54 | clients[randIndex].sendMessage(strconv.Itoa(flag)) 55 | flag++ 56 | }() 57 | } 58 | } 59 | 60 | // 写入消息 61 | func (sender *Sender) sendMessage(str string) { 62 | message := common.Message{ 63 | Token: time.Now().Format(time.RFC3339), 64 | Content: str, 65 | } 66 | sender.send <- message 67 | } 68 | 69 | // 循环发送消息 70 | func (sender *Sender) loopSendMessage() { 71 | for { 72 | m := <-sender.send 73 | if err := sender.conn.WriteJSON(m); err != nil { 74 | fmt.Println(err) 75 | } 76 | fmt.Println("发送消息", m) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /v2/chatroom.go: -------------------------------------------------------------------------------- 1 | package v2 2 | 3 | import ( 4 | "github.com/LinkinStars/simple-chatroom/common" 5 | "github.com/gorilla/websocket" 6 | "go.uber.org/zap" 7 | "net/http" 8 | "sync" 9 | "time" 10 | ) 11 | 12 | var ( 13 | chatRoom *Room 14 | ug = websocket.Upgrader{ 15 | // 允许跨域 16 | CheckOrigin: func(r *http.Request) bool { 17 | return true 18 | }, 19 | } 20 | ) 21 | 22 | // 聊天室配置 23 | type Room struct { 24 | Connections []*websocket.Conn // 连接池,保存所有连接用户 25 | sync.RWMutex 26 | } 27 | 28 | // 处理所有websocket请求 29 | func chatRoomHandle(w http.ResponseWriter, r *http.Request) { 30 | log := zap.S() 31 | conn, err := ug.Upgrade(w, r, nil) 32 | if err != nil { 33 | log.Error(err) 34 | return 35 | } 36 | defer conn.Close() 37 | 38 | // 每次有连接进来就加入连接池 39 | chatRoom.Lock() 40 | chatRoom.Connections = append(chatRoom.Connections, conn) 41 | chatRoom.Unlock() 42 | 43 | for { 44 | // 接收消息 45 | message := &common.Message{} 46 | if err := conn.ReadJSON(message); err != nil { 47 | log.Error(err) 48 | return 49 | } 50 | 51 | // 处理消息 52 | go chatRoom.batchSendMessage(*message) 53 | } 54 | } 55 | 56 | // 群发消息 57 | func (*Room) batchSendMessage(message common.Message) { 58 | chatRoom.RLock() 59 | log := zap.S() 60 | for i := 0; i < len(chatRoom.Connections); i++ { 61 | conn := chatRoom.Connections[i] 62 | if err := conn.WriteJSON(message); err != nil { 63 | log.Error("发送消息异常,移除连接") 64 | chatRoom.Lock() 65 | conn.Close() 66 | chatRoom.Connections = append(chatRoom.Connections[:i], chatRoom.Connections[i+1:]...) 67 | i-- 68 | chatRoom.Unlock() 69 | } 70 | } 71 | time.Sleep(time.Second * 2) 72 | chatRoom.RUnlock() 73 | } 74 | 75 | // 启动聊天室 76 | func StartChatRoom() { 77 | log := zap.S() 78 | log.Info("聊天室启动....") 79 | chatRoom = &Room{} 80 | http.HandleFunc("/chatroom", chatRoomHandle) 81 | if err := http.ListenAndServe(":8081", nil); err != nil { 82 | panic(err) 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /v3/chatroom.go: -------------------------------------------------------------------------------- 1 | package v3 2 | 3 | import ( 4 | "github.com/LinkinStars/simple-chatroom/common" 5 | "github.com/gorilla/websocket" 6 | "go.uber.org/zap" 7 | "net/http" 8 | ) 9 | 10 | var ( 11 | chatRoom *Room 12 | ug = websocket.Upgrader{ 13 | // 允许跨域 14 | CheckOrigin: func(r *http.Request) bool { 15 | return true 16 | }, 17 | } 18 | ) 19 | 20 | // 聊天室配置 21 | type Room struct { 22 | register chan *Client 23 | unregister chan *Client 24 | clientsPool map[*Client]bool 25 | send chan common.Message 26 | } 27 | 28 | // 处理所有websocket请求 29 | func chatRoomHandle(w http.ResponseWriter, r *http.Request) { 30 | log := zap.S() 31 | conn, err := ug.Upgrade(w, r, nil) 32 | if err != nil { 33 | log.Error(err) 34 | return 35 | } 36 | 37 | // 创建客户端 38 | c := &Client{ 39 | conn: conn, 40 | send: make(chan common.Message, 128), 41 | } 42 | 43 | go c.ReadMessage() 44 | go c.SendMessage() 45 | chatRoom.register <- c 46 | } 47 | 48 | // 处理所有管道任务 49 | func (room *Room) ProcessTask() { 50 | log := zap.S() 51 | log.Info("启动处理任务") 52 | for { 53 | select { 54 | case c := <-room.register: 55 | log.Info("当前有客户端进行注册") 56 | room.clientsPool[c] = true 57 | case c := <-room.unregister: 58 | log.Info("当前有客户端离开") 59 | if room.clientsPool[c] { 60 | close(c.send) 61 | delete(room.clientsPool, c) 62 | } 63 | case m := <-room.send: 64 | for c := range room.clientsPool { 65 | select { 66 | case c.send <- m: 67 | default: 68 | break 69 | } 70 | } 71 | } 72 | } 73 | } 74 | 75 | // 启动聊天室 76 | func StartChatRoom() { 77 | log := zap.S() 78 | log.Info("聊天室启动....") 79 | chatRoom = &Room{ 80 | register: make(chan *Client), 81 | unregister: make(chan *Client), 82 | clientsPool: map[*Client]bool{}, 83 | send: make(chan common.Message), 84 | } 85 | http.HandleFunc("/chatroom", chatRoomHandle) 86 | go chatRoom.ProcessTask() 87 | if err := http.ListenAndServe(":8081", nil); err != nil { 88 | panic(err) 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /client.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 52 | 53 | 54 | 55 | 56 | 66 | 67 |
57 |

极简聊天室

58 |
59 |

60 |

61 | 62 | 63 | 64 |
65 |
68 | 69 |
70 | 71 | 72 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # golang从简单的即时聊天来看架构演变(simple-chatroom) 2 | ## 前言 3 | 俗话说的好,架构从来都不是一蹴而就的,没有什么架构一开始设计就是最终版本,其中需要经过很多步骤的变化,今天我们就从一个最简单的例子来看看,究竟架构这个东西是怎么变的。 4 | 我将从一个最简单的聊天室的功能来实现,看看这样一个说起来好像很简单但的功能,我们需要考虑哪些问题。 5 | 6 | 我使用golang实现,从0开始实现,需要借助的是websocket来实现即时,基础知识自己补一下,这里不做过多赘述。 7 | 8 | ## 功能描述 9 | 即时聊天室包含功能(这里写出的功能假设就是产品经理告诉我们的): 10 | 1、所用用户能连接聊天室 11 | 2、连接成功的用户能向聊天室发送消息 12 | 3、所有成功连接的用户能收到聊天室的消息 13 | 14 | 为了简化,我们暂定只有一个房间,因为即使要求需要多个房间和一个房间差不多;然后我们简化消息存储,我们默认也不持久化消息,因为消息的持久化就会涉及各种数据库操作还有分页查询,这里暂时不做考虑。 15 | 16 | 那么你一定奇怪了,这些都没了,那整个实现还有啥难度?你大可以自己先想一想如果是你,你会怎么样去实现。 17 | 18 | **下文中我会用C代表客户端,S代表服务端** 19 | (本文为了展示架构的演变,如果你能想到更好的架构或者一开始就直接想到最终版本,那么证明你已经有很多的经验积累了,给大佬递茶) 20 | 21 | ## 版本1 22 | 第一个版本肯定是最简单的版本,我们就笔直朝着目标走。 23 | 我们知道websocket能实现最基本的通信。 24 | 客户端发送消息,服务端接收消息,C -> S 25 | 服务端发送消息,客户端接收消息,S -> C 26 | 27 | 那么聊天室就是:很多C发消息给S 28 | S将所有收到的消息发给**每一个**C 29 | 那么我们的第一个架构就很容易想到是这样子的: 30 | 31 | 我们在服务端维护一个连接池,连接池中保存了连接的用户,每当服务端收到一个消息之后,就遍历一遍连接池,将这个消息发送给所有连接池中的人。流程图如下: 32 | ![](doc/15559831930272.jpg) 33 | 34 | 那么下面,我们用代码来实现一下 35 | 首先定义Room里面有一个连接池 36 | ![](doc/15560015987025.jpg) 37 | 38 | 然后我们写一个处理websocket的方法 39 | ![](doc/15560016291736.jpg) 40 | 41 | 最后写一个群发消息,遍历连接池,发送消息 42 | ![](doc/15560017023669.jpg) 43 | 44 | 补全其他部分,就完成了,这就是我们第一个版本,然后我们用一个测试的html测试一下 45 | ![](doc/15560018447765.jpg) 46 | 嗯,完成啦~我真棒,真简单 47 | 48 | 当然不可能那么简单!!!还有很多问题! 49 | 针对于第一个版本,那么存在的问题还有 50 | 1、我们发现,当用户断开连接的时候,连接池里面这个连接没有被移除,所以消息发送的时候会报错,而且连接池会一直变大。 51 | 2、用户很多,遍历发送消息是一个耗时的操作,不应该被阻塞 52 | 53 | 针对这两个问题改动如下: 54 | 1、当发送消息失败,证明连接已经断开,所以从连接池中移除连接 55 | 2、群发消息改为gorutinue 56 | 57 | ## 版本1.1 58 | 所以V1.1修改如下 59 | ![](doc/15560059607703.jpg) 60 | 61 | ![](doc/15560059511302.jpg) 62 | 63 | 到此为止,第一个版本就到这里了,因为聪明的你应该已经发现这样设计的架构存在一个巨大的问题... 64 | 65 | ## 版本2 66 | 如果你有一定的并发编程的经验就会发现,上面版本有一个很危险的并发操作,那就是连接池。 67 | 68 | - 连接池的并发操作: 69 | 新的用户进来需要添加入连接池 70 | 如果用户断开连接需要移出连接池 71 | 每次发送消息需要遍历连接池 72 | 73 | 我们假设一种情况,当一个协程正在遍历连接池发送消息的时候,另外一个协程把其中一些连接删除了,还有一个协程把新的连接加进去了,这样的操作就是传说中的并发问题。 74 | 75 | 而且对于websocket来说还有一个问题,就是如果并发去对同一个连接发送消息的话就会出现panic: concurrent write to websocket connection这样的异常,因为是panic所以问题就非常大了。 76 | 77 | 并发问题怎么解决?很多人会说,简单,加锁就完事了 78 | ![](doc/15560094190704.jpg) 79 | ![](doc/15560094299023.jpg) 80 | ![](doc/15560094387666.jpg) 81 | 加完了,搞定,这下没问题了吧。这就是版本2。因为加入了锁机制,所以并发安全保证了,但是 82 | 新的问题又出现了,我们如果我们在发送消息的方法中加入延时,模拟出发送消息网络不正常的情况 83 | time.Sleep(time.Second * 2) 84 | 那么你就会发现,当新的用户加入的时候,因为当前还有消息正在发送,所以导致新加入的用户没有办法获取到锁,也就无法发送消息 85 | 那怎么办呢? 86 | 87 | 然后顺便说一下,因为锁的是room在一定并发的程度上还是有可能出现异常 88 | ![](doc/15560900273343.jpg) 89 | 90 | 91 | ## 版本3 92 | 我在开发golang的时候有这样一个信念,有锁的地方一定能用channel优化,从而面向并发编程,虽然并非绝对,但是golang提供的channel很多情况下都能将锁给替换掉,从而换取出性能的提升,具体怎么做呢? 93 | 首先我们想一下有哪些地方可以利用channel进行解耦 94 | 1、第一次连接,我们将连接扔进一个信道中去 95 | 2、断开连接,我们将要删除的连接扔进一个信道中去 96 | 3、发送消息,我们每个连接对象都有一个信道,只需要将消息写入这个信道就能发送消息 97 | 98 | 所以我们重新调整一下架构,图如下: 99 | ![](doc/15560126952552.jpg) 100 | 101 | 然后我们看看代码上面如何实现: 102 | 103 | 首先定义一个客户端 104 | ![](doc/15560726975250.jpg) 105 | 包含一个连接和一个发送消息的专用信道 106 | 然后定义客户端的两个方法 107 | ![](doc/15560774419983.jpg) 108 | 109 | 当从websocket中获取到信息的时候,将消息丢到chatRoom的总发送信道中去,由chatRoom去群发。 110 | 当自己的send信道中有消息时,将消息通过websocket发送给客户端。 111 | 同时当发送或者接收消息出现异常,将自己发送给取消注册的信道,由chatRoom去移除注册信息。 112 | 113 | 然后定义聊天室 114 | ![](doc/15560729656703.jpg) 115 | register用于处理注册 116 | unregister用于处理移除注册 117 | clientsPool这里更换为map,方便移除 118 | send是总发送消息信道,用于群发消息 119 | 120 | 然后定义处理websocket方法 121 | ![](doc/15560730272299.jpg) 122 | 当前第一次来的时候就创建客户端,然后启动客户端的读取和发送方法,并且将自己发给注册信道 123 | 124 | 最后最重要的就是如何去调度处理chatRoom中所有的管道,我们使用select 125 | ![](doc/15560849239804.jpg) 126 | 127 | 当有注册的时候就注册,当有离开的时候就删除,当需要发送消息的时候,消息会发送给每一个client各自的send信道由它们自己发送。 128 | 这样就成功实现了使用channel代替了原来的锁 129 | ![](doc/15560776646355.jpg) 130 | 当前群发消息和客户的加入退出就基本不受到影响了,随时可以加入和退出,一旦加入就会收到消息。 131 | 一切看似很完美吧,其实还有些bug,我们创建一些客户端进行压测试试看。 132 | 133 | ## 版本3.1 134 | 编写压测代码如下,因为压测就是创建很多客户端发送消息,这里就不多做赘述了 135 | ![](doc/15560923838579.jpg) 136 | ![](doc/15560924007549.jpg) 137 | 138 | 然后会发现,测试的过程中,如果你启动一个网页版本的客户端发现,你的消息发不出去了。这是为什么呢? 139 | 原来我们之前在处理所有管道中任务的时候当处理发送消息的时候有问题,虽然send是一个有缓冲的通道,但是当缓冲满的时候,那么就会阻塞,无法向里面再发送消息,需要等待send里面的消息被消费,但是如果send里面的消息要被消费,前提就是要轮到这个消息被发送,于是造成了循环等待,一定意义上的死锁。(有点绕,你需要理一理) 140 | ![](doc/15560925944012.jpg) 141 | 所以我们需要修改一下代码,修复这个bug,当消息无法写入send信道的时候,那就直接将这个消息抛弃(虽然这样处理好像不太科学),因为要不就是这个用户已经断开连接,要不就是这个用户的缓冲信道已经占满了。如下: 142 | ![](doc/15560929305585.jpg) 143 | 144 | ## 版本3.2 145 | 其实在做的过程中就发现了一些问题,一个问题同一个用户如果不停的发送消息,那么一方面是会对服务器造成压力,另一方面对于别的用户来说这是一种骚扰,所以我们需要限制用户发送消息的频率。这里为了测试方便,针对于同一个用户1秒内只能发送一条消息,这样从一定程度上也减少了并发问题的出现。 146 | 147 | 改动非常简单,如下: 148 | ![](doc/15560975312422.jpg) 149 | 150 | 我们启动多个客户端定时的发送一些消息进行测试,5个客户端下每1ms发送一条消息,本机测试下来没有问题。 151 | 152 | ## 后续版本 153 | 那么到现在我们已经实际了聊天室的基本功能,对于一个最简单的聊天来说已经足够了,但是因为我们简化了很多细节,所以存在很多优化的地方,下面列举几个地方可以做后续的优化和升级。 154 | 155 | 1、消息持久化,当前消息发送之后如果当时用户不在线就无法收到,这样对于用户来说其实是很难受的,所以消息需要进行持久化,而持久化就会有很多方案,保存消息的方式,以及保存消息的时间,不能因为保存消息而影响即时性。以及用户再次登录之后需要将之后保存的消息返回给用户。 156 | 157 | 2、消息id,我们现在发送消息的时候是不带消息id的,但是其实作为消息本身,消息的发送需要保证幂等性,相同的消息(消息id相同)不应该发送多次,所以消息id的生成,如何保证消息不重复也是需要考虑的。 158 | 159 | 3、消息不丢失,消息持久化,网络异常都有可能导致消息丢失,如何保证消息不丢失呢? 160 | 161 | 4、密集型消息分发,当用户人数很多,当前会创建很多的协程去分发消息,人一多肯定就不行了,而且人一多,一台机器肯定不够,那么分布式维护连接池等等架构的调整就需要进行了。 162 | 163 | 5、心跳保活,连接一段时间之后,由于网络的原因或者别的原因,可能会导致连接中断的情况出现,所以经过一段时间就需要发送一些消息保持连接。类似PING\PONG 164 | 165 | 6、鉴权,这个简单,当前任何用户连上就能发送消息,理论上来说,其实需要经过鉴权之后才能发送消息。 166 | 167 | 7、消息加密,现在消息都是明文传输的,这样传递消息其实是不安全的,所以加密传输消息也是后期可以考虑的,同时消息的压缩也是。 168 | 169 | 这些后续的扩展就要你来思考一下了,如何去实现。设计的时候你也可以参考很多现实中已经存在的一些例子来帮助你思考。在我们实现的时候也没有借助任何的中间件,所以你可以后期考虑使用一些中间件来完成分布式等要求,如mq等。 170 | 171 | 是不是看到这里发现只是简单的一个即时聊天后面的架构扩展都是非常可怕的,如果真的要做到像微信或者qq那样随意的单聊和群聊,并且解决各种并发问题还有很多路要走。 172 | 173 | ## 总结 174 | 这里其实想说明的并不是如何去设计一个IM,想要真正说明的是一个架构师如何进行演变的,其中需要考虑到哪些问题,这些问题又是如何被解决的。其中需要经历不断的测试,调整,测试,调整。还想说明的是,架构没有好和坏,只有适合与否,对于一个小的项目来说就没有必要用大架构,合适的才是最好的。 175 | 176 | 最后,也肯定有人想了解一些大型的聊天im的架构,这里有几篇博客我认为写的很不错,可以参考一下。 177 | 178 | 下面这两篇是对一些大型架构的说明 179 | https://alexstocks.github.io/html/pubsub.html 180 | https://alexstocks.github.io/html/im.html 181 | 182 | 下面是一些github上的项目 183 | https://github.com/alberliu/goim 184 | 这个项目比较简单,容易理解,文档介绍详细解释了很多概念,具体使用nsq来实现消息的转发 185 | 186 | https://github.com/Terry-Mao/goim 187 | 这个项目相对复杂 188 | 189 | 190 | 191 | 192 | 193 | 194 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------