侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

golang实现简易的分布式系统方法

Go  /  管理员 发布于 7年前   214

本文介绍了golang实现简易的分布式系统方法,分享给大家,具体如下:

功能

  • 能够发送/接收请求和响应
  • 能够连接到集群
  • 如果无法连接到群集(如果它是第一个节点),则可以作为主节点启动节点
  • 每个节点有唯一的标识
  • 能够在节点之间交换json数据包
  • 接受命令行参数中的所有信息(将来在我们系统升级时将会很有用)

源码

package mainimport (  "fmt"  "strconv"  "time"  "math/rand"  "net"  "flag"  "strings"  "encoding/json")// 节点数据信息type NodeInfo struct {  // 节点ID,通过随机数生成  NodeId int `json:"nodeId"`  // 节点IP地址  NodeIpAddr string `json:"nodeIpAddr"`  // 节点端口  Port string `json: "port"`}// 将节点数据信息格式化输出//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 + "}"}/* 添加一个节点到集群的一个请求或者响应的标准格式 */type AddToClusterMessage struct {  // 源节点  Source NodeInfo `json:"source"`  // 目的节点  Dest NodeInfo `json:"dest"`  // 两个节点连接时发送的消息  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// rmfunc main() {  // 解析命令行参数  makeMasterOnError := flag.Bool("makeMasterOnError", false, "如果IP地址没有连接到集群中,我们将其作为Master节点.")  clusterip := flag.String("clusterip", "127.0.0.1:8001", "任何的节点连接都连接这个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)  /* 为节点生成ID */  rand.Seed(time.Now().UTC().UnixNano()) //种子  myid := rand.Intn(99999999) // 随机  //fmt.Println(myid)  // 获取IP地址  myIp,_ := net.InterfaceAddrs()  fmt.Println(myIp[0])  // 创建NodeInfo结构体对象  me := NodeInfo{NodeId: myid, NodeIpAddr: myIp[0].String(), Port: *myport}  // 输出结构体数据信息  fmt.Println(me.String())  dest := NodeInfo{ NodeId: -1, NodeIpAddr: strings.Split(*clusterip, ":")[0], Port: strings.Split(*clusterip, ":")[1]}  /* 尝试连接到集群,在已连接的情况下并且向集群发送请求 */  ableToConnect := connectToCluster(me, dest)  /*   * 监听其他节点将要加入到集群的请求   */  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)  }}/* * 这是发送请求时格式化json包有用的工具 * 这是非常重要的,如果不经过数据格式化,你最终发送的将是空白消息 */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的相关细节信息 */  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("连接到集群. 发送消息到节点.")    text := "Hi nody.. 请添加我到集群.."    requestMessage := getAddToClusterMessage(me, dest, text)    json.NewEncoder(connOut).Encode(&requestMessage)    decoder := json.NewDecoder(connOut)    var responseMessage AddToClusterMessage    decoder.Decode(&responseMessage)    fmt.Println("得到数据响应:\n" + responseMessage.String())    return true  }  return false}func listenOnPort(me NodeInfo){  /* 监听即将到来的消息 */  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/goliyuechun:go yuechunli$ go install mainliyuechun:go yuechunli$ mainMy details: NodeInfo:{ nodeId:53163002, nodeIpAddr:127.0.0.1/8, port:8001 }不能连接到集群. 53163002Quitting system. Set makeMasterOnError flag to make the node master. 53163002liyuechun:go yuechunli$

获取相关帮助信息

$ ./bin/main -h
liyuechun:go yuechunli$ ./bin/main -hUsage 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主节点

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

添加节点Node2到集群

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

添加节点Node3到集群

main --myport 8004 --clusterip 127.0.0.1:8001

添加节点Node4到集群

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    详解golang consul-grpc 服务注册与发现
    下一条:
    Golang获取当前时间代码
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-09
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-12
    • 2021-01
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-08
    • 2024-11
    • 2025-02
    • 2025-04
    • 2025-05
    • 2025-06
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客