Golang Development of Engineering experience (I.)
1, custom structure maintenance user and corresponding TCP link
You can use map to maintain this information, but once you have a large number of connected users, the map is too big to reduce the efficiency of the query, so you can customize the structure:
type User struct { uid int64 conn *CConn ticked bool // 多次连接导致当前连接被踢下 beatTimeOut bool // 心跳检测超时 ...}type CConn struct{ conn net.Conn // 网络连接 lastTime time.Time // 最近一次通信时间 addr string // 连接的唯一标识符 user *User // User与CConn一一映射}
Then when the connection is established
Func clistenandserve (NET, addr string) {tcpaddr, err: = Net. RESOLVETCPADDR (NET,ADDR) if err! = Nil {//error handling} listener, err: = Net.listentcp (NET, tcpaddr) If err! = Nil {//error handling} go Accept ()//Because the go path creation overhead is very small}func accpet () {for {conn, err : = Listener. ACCEPTTCP () If Err = = Nil {//Bundle frequency statistics, avoid frequent connections//black and white list newconn: = NEWCCONN (conn)// Create Cconn Newconn. Run ()} else {//error handling}}}FUNC (conn *cconn) run () {conn.onconnect () go func () {tickerrecv: = time. Newticker (time. Second * time. Duration (Ratestatinterval)) for {select {case <-conn. StopChan:tickerRecv.Stop () return case <-TICKERRECV.C:CONN.P ACKETRECV = 0 Default:conn_closed: = CONN.PARSEANDHANDLEPDU () if conn_closed{Tickerrecv.stop () Return}}} ()}func (conn *cconn) OnConnect () * User {User: = &user{conn:conn, ...//Other initialization content}}
Each connection is handled with a go process, which allows each connection to be independent and, of course, a point that the number of connections per service node should have a time-limited policy.
2, get ready-to-use single-case mode
import "github.com/dropbox/godropbox/singleton"var singleSrv = singleton.NewSingleton(func() (interface{}, error) { cluster, _ := cache.GetRedisCluster("singlecache") return &SingleMsgProxy{ Cluster: cluster, MsgModel: msg.MsgModel, }, nil})
3, generic type
type MyInterface interface { Len() int Less(i, j int) bool Swap(i, j int)}func CustomSort(d MyInterface) { ...}
Regardless of the type of D that uses customesort, you can use the Customsort function as long as you implement Len () less () Swap () as required by the interface.