Преглед на файлове

向 PHP 服务发送未读消息通知

shizhongqi преди 11 месеца
родител
ревизия
361e009d31
променени са 7 файла, в които са добавени 181 реда и са изтрити 2 реда
  1. 1 1
      .cursor/general_rules.mdc
  2. 4 1
      .env.example
  3. 52 0
      external/huaHuiBao.go
  4. 52 0
      external/huaZhangGui.go
  5. 54 0
      external/request.go
  6. 13 0
      wsClient/redis.go
  7. 5 0
      wsClient/room.go

+ 1 - 1
.cursor/general_rules.mdc

@@ -7,7 +7,7 @@ alwaysApply: true
 
 
 ## 1. 技术选型与库使用
 ## 1. 技术选型与库使用
 
 
-- **首选库**: 本项目统一使用 `github.com/gorilla/websocket` 库来处理 WebSocket 连接。它是目前功能最完善、社区支持最广泛的 Go WebSocket 库。
+- **首选库**: 本项目统一使用 `github.com/gorilla/websocket` 库来处理 WebSocket 连接。
 - **禁止使用**: 除非有特殊理由,请**避免**直接使用标准库 `golang.org/x/net/websocket`,因为它缺少一些高级功能和性能优化。
 - **禁止使用**: 除非有特殊理由,请**避免**直接使用标准库 `golang.org/x/net/websocket`,因为它缺少一些高级功能和性能优化。
 
 
 ## 2. WebSocket 连接处理
 ## 2. WebSocket 连接处理

+ 4 - 1
.env.example

@@ -3,4 +3,7 @@ LOG_LEVEL=0
 
 
 REDIS_ADDR=118.178.193.23:6379
 REDIS_ADDR=118.178.193.23:6379
 REDIS_PASSWORD=byt6gc1w0aed2q7h
 REDIS_PASSWORD=byt6gc1w0aed2q7h
-REDIS_DB=0
+REDIS_DB=0
+
+HUA_ZHANG_GUI_URL=https://api.shop.huahb.cn/chat/message-server-call
+HUA_HUI_BAO_URL=https://api.shop.zhiguanhua.cn/chat/message-server-call

+ 52 - 0
external/huaHuiBao.go

@@ -0,0 +1,52 @@
+package external
+
+import (
+	"bytes"
+	"context"
+	"encoding/json"
+	"io/ioutil"
+	"net/http"
+	"time"
+)
+
+type HuaHuiBaoClient interface {
+    GetWeather(ctx context.Context, city string) (string, error)
+	PostUnReadMessage(ctx context.Context, reqData UnreadMessageRequest) (string, error)
+}
+
+type huaHuiBaoClient struct {
+    httpClient *http.Client
+    baseURL    string
+}
+
+func NewHuaHuiBaoClient(baseURL string) HuaHuiBaoClient {
+    return &huaHuiBaoClient{
+        httpClient: &http.Client{Timeout: 5 * time.Second},
+        baseURL:    baseURL,
+    }
+}
+
+func (c *huaHuiBaoClient) GetWeather(ctx context.Context, city string) (string, error) {
+    req, _ := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/weather?city="+city, nil)
+    resp, err := c.httpClient.Do(req)
+    if err != nil {
+        return "", err
+    }
+    defer resp.Body.Close()
+
+    body, _ := ioutil.ReadAll(resp.Body)
+    return string(body), nil
+}
+
+func (c *huaHuiBaoClient) PostUnReadMessage(ctx context.Context, reqData UnreadMessageRequest) (string, error) {
+    jsonData, _ := json.Marshal(reqData)
+    req, _ := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/unread_message", bytes.NewBuffer(jsonData))
+    req.Header.Set("Content-Type", "application/json")
+    resp, err := c.httpClient.Do(req)
+    if err != nil {
+        return "", err
+    }
+    defer resp.Body.Close()
+    body, _ := ioutil.ReadAll(resp.Body)
+    return string(body), nil
+}

+ 52 - 0
external/huaZhangGui.go

@@ -0,0 +1,52 @@
+package external
+
+import (
+	"bytes"
+	"context"
+	"encoding/json"
+	"io/ioutil"
+	"net/http"
+	"time"
+)
+
+type HuaZhangGuiClient interface {
+    GetWeather(ctx context.Context, city string) (string, error)
+	PostUnReadMessage(ctx context.Context, reqData UnreadMessageRequest) (string, error)
+}
+
+type huaZhangGuiClient struct {
+    httpClient *http.Client
+    baseURL    string
+}
+
+func NewHuaZhangGuiClient(baseURL string) HuaZhangGuiClient {
+    return &huaZhangGuiClient{
+        httpClient: &http.Client{Timeout: 5 * time.Second},
+        baseURL:    baseURL,
+    }
+}
+
+func (c *huaZhangGuiClient) GetWeather(ctx context.Context, city string) (string, error) {
+    req, _ := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/weather?city="+city, nil)
+    resp, err := c.httpClient.Do(req)
+    if err != nil {
+        return "", err
+    }
+    defer resp.Body.Close()
+
+    body, _ := ioutil.ReadAll(resp.Body)
+    return string(body), nil
+}
+
+func (c *huaZhangGuiClient) PostUnReadMessage(ctx context.Context, reqData UnreadMessageRequest) (string, error) {
+    jsonData, _ := json.Marshal(reqData)
+    req, _ := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/unread_message", bytes.NewBuffer(jsonData))
+    req.Header.Set("Content-Type", "application/json")
+    resp, err := c.httpClient.Do(req)
+    if err != nil {
+        return "", err
+    }
+    defer resp.Body.Close()
+    body, _ := ioutil.ReadAll(resp.Body)
+    return string(body), nil
+}

+ 54 - 0
external/request.go

@@ -0,0 +1,54 @@
+package external
+
+import (
+	"context"
+	"os"
+)
+
+
+type UnreadMessageRequest struct {
+    Type string `json:"type"`
+    Id int32 `json:"id"`
+    MsgCount int `json:"msgCount"`
+}
+
+// 请求函数 -- 根据请求项目选择请求方式
+func RequestToPHP(receiverType string, receiverID int32, count int) error {
+	var project string
+	if receiverType == "shop" {
+		project = "huaZhangGui"
+	} else if receiverType == "customer" {
+		project = "huaHuiBao"
+	}
+
+	ctx := context.Background()
+	switch project {
+	case "huaZhangGui":
+		url := os.Getenv("HUA_ZHANG_GUI_URL")
+		reqData := UnreadMessageRequest{
+			Type: "shop",
+			Id: receiverID,
+			MsgCount: count,
+		}
+		huaZhangGuiClient := NewHuaZhangGuiClient(url)
+		_, err := huaZhangGuiClient.PostUnReadMessage(ctx, reqData)
+		if err != nil {
+			return err
+		}
+		
+	case "huaHuiBao":
+		url := os.Getenv("HUA_HUI_BAO_URL")
+		reqData := UnreadMessageRequest{
+			Type: "customer",
+			Id: receiverID,
+			MsgCount: count,
+		}
+		huaHuiBaoClient := NewHuaHuiBaoClient(url)
+		_, err := huaHuiBaoClient.PostUnReadMessage(ctx, reqData)
+		if err != nil {
+			return err
+		}
+	}
+
+	return nil
+}

+ 13 - 0
wsClient/redis.go

@@ -373,6 +373,19 @@ func parseScore(score float64) (timestamp int64, unreadCount int) {
 	return
 	return
 }
 }
 
 
+// 生成发送者和接收者的信息
+// @param sender 发送者
+// @param count 未读消息数
+// @return 接收者类型, 接收者ID, 未读消息数
+func GeneHaveSendInfo(sender *Client, count int) (string, int32, int) {
+	if sender.userInfo.Type == UserTypeShop {
+		return UserTypeCustomer, sender.userInfo.UserId, count
+	} else if sender.userInfo.Type == UserTypeCustomer {
+		return UserTypeShop, sender.userInfo.ShopId, count
+	}
+	return "", 0, 0
+}
+
 /**
 /**
 * 生成联系人的Redis键
 * 生成联系人的Redis键
 * @param userType 用户类型
 * @param userType 用户类型

+ 5 - 0
wsClient/room.go

@@ -11,6 +11,8 @@ import (
 	"strings"
 	"strings"
 	"sync"
 	"sync"
 
 
+	"chatapp/external"
+
 	"github.com/gorilla/websocket"
 	"github.com/gorilla/websocket"
 	"github.com/rs/zerolog/log"
 	"github.com/rs/zerolog/log"
 )
 )
@@ -157,6 +159,9 @@ func (r *Room) run() {
 			// 本消息转发,目的是让客户与门店互相发消息,当有另一方不在线时,要累计未读消息数
 			// 本消息转发,目的是让客户与门店互相发消息,当有另一方不在线时,要累计未读消息数
 			if !online {
 			if !online {
 				go IncrementUnreadCount(msg.sender, 1)
 				go IncrementUnreadCount(msg.sender, 1)
+				receiverType, receiverID, count := GeneHaveSendInfo(msg.sender, 1)
+				// 向 PHP 服务发送未读消息通知
+				go external.RequestToPHP(receiverType, receiverID, count)
 			}
 			}
 		}
 		}
 	}
 	}