开始写交易所后端行情模块
作者:
迷弟
,
2024-07-04 22:41:19
,
所有人可见
,
阅读 20
- 从内存里获取,以保证绝对速度。
- 改进版:从redis里获取保证一致性。可以借助redis自身的Raft算法。
- 开码字开码!Let’s Start Coding~ Yeah
package main
import (
"encoding/json"
"log"
"math/rand"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
type MarketPrice struct {
Price float64 `json:"price"`
Timestamp int64 `json:"timestamp"`
}
var (
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // Allow all connections for this example
},
}
clients = make(map[*websocket.Conn]bool)
clientsLock sync.RWMutex
broadcast = make(chan MarketPrice)
)
func main() {
// Start the price updater
go priceUpdater()
// Start the broadcaster
go broadcaster()
// Set up HTTP server
http.HandleFunc("/ws", handleConnections)
log.Println("Server starting on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
defer ws.Close()
clientsLock.Lock()
clients[ws] = true
clientsLock.Unlock()
for {
_, _, err := ws.ReadMessage()
if err != nil {
clientsLock.Lock()
delete(clients, ws)
clientsLock.Unlock()
break
}
}
}
func broadcaster() {
for {
price := <-broadcast
clientsLock.RLock()
for client := range clients {
err := client.WriteJSON(price)
if err != nil {
log.Printf("error: %v", err)
client.Close()
delete(clients, client)
}
}
clientsLock.RUnlock()
}
}
func priceUpdater() {
basePrice := 50000.0
for {
// Simulate price changes
change := (rand.Float64() - 0.5) * 10
newPrice := basePrice + change
if newPrice < 0 {
newPrice = 0
}
basePrice = newPrice
price := MarketPrice{
Price: newPrice,
Timestamp: time.Now().UnixNano() / int64(time.Millisecond),
}
broadcast <- price
// Update every 100ms
time.Sleep(100 * time.Millisecond)
}
}