佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > golang實現(xiàn)簡易的分布式系統(tǒng)方法

golang實現(xiàn)簡易的分布式系統(tǒng)方法

熱門標簽:百度競價排名 鐵路電話系統(tǒng) 服務外包 呼叫中心市場需求 地方門戶網站 Linux服務器 AI電銷 網站排名優(yōu)化

本文介紹了golang實現(xiàn)簡易的分布式系統(tǒng)方法,分享給大家,具體如下:

功能

  • 能夠發(fā)送/接收請求和響應
  • 能夠連接到集群
  • 如果無法連接到群集(如果它是第一個節(jié)點),則可以作為主節(jié)點啟動節(jié)點
  • 每個節(jié)點有唯一的標識
  • 能夠在節(jié)點之間交換json數(shù)據包
  • 接受命令行參數(shù)中的所有信息(將來在我們系統(tǒng)升級時將會很有用)

源碼

package main

import (
  "fmt"
  "strconv"
  "time"
  "math/rand"
  "net"
  "flag"
  "strings"
  "encoding/json"
)

// 節(jié)點數(shù)據信息
type NodeInfo struct {

  // 節(jié)點ID,通過隨機數(shù)生成
  NodeId int `json:"nodeId"`
  // 節(jié)點IP地址
  NodeIpAddr string `json:"nodeIpAddr"`
  // 節(jié)點端口
  Port string `json: "port"`
}

// 將節(jié)點數(shù)據信息格式化輸出
//NodeInfo:{nodeId: 89423,nodeIpAddr: 127.0.0.1/8,port: 8001}
func (node *NodeInfo) String() string {

  return "NodeInfo:{ nodeId:" + strconv.Itoa(node.NodeId) + ",nodeIpAddr:" + node.NodeIpAddr + ",port:" + node.Port + "}"
}

/* 添加一個節(jié)點到集群的一個請求或者響應的標準格式 */
type AddToClusterMessage struct {
  // 源節(jié)點
  Source NodeInfo `json:"source"`
  // 目的節(jié)點
  Dest NodeInfo `json:"dest"`
  // 兩個節(jié)點連接時發(fā)送的消息
  Message string `json:"message"`
}

/* Request/Response 信息格式化輸出 */
func (req AddToClusterMessage) String() string {
  return "AddToClusterMessage:{\n source:" + req.Source.String() + ",\n dest: " + req.Dest.String() + ",\n message:" + req.Message + " }"
}

// cat vi go
// rm

func main() {

  // 解析命令行參數(shù)
  makeMasterOnError := flag.Bool("makeMasterOnError", false, "如果IP地址沒有連接到集群中,我們將其作為Master節(jié)點.")
  clusterip := flag.String("clusterip", "127.0.0.1:8001", "任何的節(jié)點連接都連接這個IP")
  myport := flag.String("myport", "8001", "ip address to run this node on. default is 8001.")
  flag.Parse() //解析

  fmt.Println(*makeMasterOnError)
  fmt.Println(*clusterip)
  fmt.Println(*myport)

  /* 為節(jié)點生成ID */
  rand.Seed(time.Now().UTC().UnixNano()) //種子
  myid := rand.Intn(99999999) // 隨機

  //fmt.Println(myid)

  // 獲取IP地址
  myIp,_ := net.InterfaceAddrs()
  fmt.Println(myIp[0])

  // 創(chuàng)建NodeInfo結構體對象
  me := NodeInfo{NodeId: myid, NodeIpAddr: myIp[0].String(), Port: *myport}
  // 輸出結構體數(shù)據信息
  fmt.Println(me.String())
  dest := NodeInfo{ NodeId: -1, NodeIpAddr: strings.Split(*clusterip, ":")[0], Port: strings.Split(*clusterip, ":")[1]}

  /* 嘗試連接到集群,在已連接的情況下并且向集群發(fā)送請求 */
  ableToConnect := connectToCluster(me, dest)

  /*
   * 監(jiān)聽其他節(jié)點將要加入到集群的請求
   */
  if ableToConnect || (!ableToConnect  *makeMasterOnError) {
    if *makeMasterOnError {fmt.Println("Will start this node as master.")}
    listenOnPort(me)
  } else {
    fmt.Println("Quitting system. Set makeMasterOnError flag to make the node master.", myid)
  }

}

/*
 * 這是發(fā)送請求時格式化json包有用的工具
 * 這是非常重要的,如果不經過數(shù)據格式化,你最終發(fā)送的將是空白消息
 */
func getAddToClusterMessage(source NodeInfo, dest NodeInfo, message string) (AddToClusterMessage){
  return AddToClusterMessage{
    Source: NodeInfo{
      NodeId: source.NodeId,
      NodeIpAddr: source.NodeIpAddr,
      Port: source.Port,
    },
    Dest: NodeInfo{
      NodeId: dest.NodeId,
      NodeIpAddr: dest.NodeIpAddr,
      Port: dest.Port,
    },
    Message: message,
  }
}

func connectToCluster(me NodeInfo, dest NodeInfo) (bool){
  /* 連接到socket的相關細節(jié)信息 */
  connOut, err := net.DialTimeout("tcp", dest.NodeIpAddr + ":" + dest.Port, time.Duration(10) * time.Second)
  if err != nil {
    if _, ok := err.(net.Error); ok {
      fmt.Println("未連接到集群.", me.NodeId)
      return false
    }
  } else {
    fmt.Println("連接到集群. 發(fā)送消息到節(jié)點.")
    text := "Hi nody.. 請?zhí)砑游业郊?."
    requestMessage := getAddToClusterMessage(me, dest, text)
    json.NewEncoder(connOut).Encode(requestMessage)

    decoder := json.NewDecoder(connOut)
    var responseMessage AddToClusterMessage
    decoder.Decode(responseMessage)
    fmt.Println("得到數(shù)據響應:\n" + responseMessage.String())

    return true
  }
  return false
}

func listenOnPort(me NodeInfo){
  /* 監(jiān)聽即將到來的消息 */
  ln, _ := net.Listen("tcp", fmt.Sprint(":" + me.Port))
  /* 接受連接 */
  for {
    connIn, err := ln.Accept()
    if err != nil {
      if _, ok := err.(net.Error); ok {
        fmt.Println("Error received while listening.", me.NodeId)
      }
    } else {
      var requestMessage AddToClusterMessage
      json.NewDecoder(connIn).Decode(requestMessage)
      fmt.Println("Got request:\n" + requestMessage.String())

      text := "Sure buddy.. too easy.."
      responseMessage := getAddToClusterMessage(me, requestMessage.Source, text)
      json.NewEncoder(connIn).Encode(responseMessage)
      connIn.Close()
    }
  }
}

運行程序

/Users/liyuechun/go
liyuechun:go yuechunli$ go install main
liyuechun:go yuechunli$ main
My details: NodeInfo:{ nodeId:53163002, nodeIpAddr:127.0.0.1/8, port:8001 }
不能連接到集群. 53163002
Quitting system. Set makeMasterOnError flag to make the node master. 53163002
liyuechun:go yuechunli$

獲取相關幫助信息

$ ./bin/main -h
liyuechun:go yuechunli$ ./bin/main -h
Usage of ./bin/main:
 -clusterip string
    ip address of any node to connnect (default "127.0.0.1:8001")
 -makeMasterOnError
    make this node master if unable to connect to the cluster ip provided.
 -myport string
    ip address to run this node on. default is 8001. (default "8001")
liyuechun:go yuechunli$

啟動Node1主節(jié)點

$ ./bin/main --makeMasterOnError
liyuechun:go yuechunli$ ./bin/main --makeMasterOnError
My details: NodeInfo:{ nodeId:82381143, nodeIpAddr:127.0.0.1/8, port:8001 }
未連接到集群. 82381143
Will start this node as master.

添加節(jié)點Node2到集群

$ ./bin/main --myport 8002 --clusterip 127.0.0.1:8001

添加節(jié)點Node3到集群

main --myport 8004 --clusterip 127.0.0.1:8001

添加節(jié)點Node4到集群

$ main --myport 8003 --clusterip 127.0.0.1:8002

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • GO語言實現(xiàn)簡單的目錄復制功能
  • Go語言實現(xiàn)互斥鎖、隨機數(shù)、time、List
  • Golang獲取當前時間代碼
  • Golang字符串的拼接方法匯總
  • Go語言中 Channel 詳解
  • go語言中strings包的用法匯總
  • Golang中的變量學習小結
  • Golang中的自定義函數(shù)詳解
  • 在Go中復制文件最流行的3種方法

標簽:湘潭 崇左 黃山 衡水 仙桃 湖南 蘭州 銅川

巨人網絡通訊聲明:本文標題《golang實現(xiàn)簡易的分布式系統(tǒng)方法》,本文關鍵詞  ;如發(fā)現(xiàn)本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    龙泉市| 南召县| 开远市| 汝州市| 秭归县| 肥西县| 定州市| 科尔| 民县| 大田县| 洞头县| 阿巴嘎旗| 东安县| 龙口市| 宣威市| 垣曲县| 临沂市| 井研县| 女性| 清河县| 鄂尔多斯市| 民乐县| 青阳县| 内黄县| 南通市| 沽源县| 宣威市| 太和县| 阿荣旗| 凯里市| 剑河县| 合肥市| 澳门| 仁化县| 团风县| 梨树县| 陕西省| 宁波市| 海阳市| 庐江县| 分宜县|