热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

这篇文章主要介绍了golang实现简易的分布式系统方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

功能

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

源码

package main

import (
  "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
// rm

func 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/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主节点

$ ./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.

添加节点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

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


推荐阅读
  • SpringBoot整合SpringSecurity+JWT实现单点登录
    SpringBoot整合SpringSecurity+JWT实现单点登录,Go语言社区,Golang程序员人脉社 ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • t-io 2.0.0发布-法网天眼第一版的回顾和更新说明
    本文回顾了t-io 1.x版本的工程结构和性能数据,并介绍了t-io在码云上的成绩和用户反馈。同时,还提到了@openSeLi同学发布的t-io 30W长连接并发压力测试报告。最后,详细介绍了t-io 2.0.0版本的更新内容,包括更简洁的使用方式和内置的httpsession功能。 ... [详细]
  • 本文介绍了Hyperledger Fabric外部链码构建与运行的相关知识,包括在Hyperledger Fabric 2.0版本之前链码构建和运行的困难性,外部构建模式的实现原理以及外部构建和运行API的使用方法。通过本文的介绍,读者可以了解到如何利用外部构建和运行的方式来实现链码的构建和运行,并且不再受限于特定的语言和部署环境。 ... [详细]
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • 一句话解决高并发的核心原则
    本文介绍了解决高并发的核心原则,即将用户访问请求尽量往前推,避免访问CDN、静态服务器、动态服务器、数据库和存储,从而实现高性能、高并发、高可扩展的网站架构。同时提到了Google的成功案例,以及适用于千万级别PV站和亿级PV网站的架构层次。 ... [详细]
  • 本文介绍了如何使用jQuery和AJAX来实现动态更新两个div的方法。通过调用PHP文件并返回JSON字符串,可以将不同的文本分别插入到两个div中,从而实现页面的动态更新。 ... [详细]
  • Sleuth+zipkin链路追踪SpringCloud微服务的解决方案
    在庞大的微服务群中,随着业务扩展,微服务个数增多,系统调用链路复杂化。Sleuth+zipkin是解决SpringCloud微服务定位和追踪的方案。通过TraceId将不同服务调用的日志串联起来,实现请求链路跟踪。通过Feign调用和Request传递TraceId,将整个调用链路的服务日志归组合并,提供定位和追踪的功能。 ... [详细]
  • 本文介绍了iOS开发中检测和解决内存泄漏的方法,包括静态分析、使用instruments检查内存泄漏以及代码测试等。同时还介绍了最能挣钱的行业,包括互联网行业、娱乐行业、教育行业、智能行业和老年服务行业,并提供了选行业的技巧。 ... [详细]
  • 本文讨论了在使用Git进行版本控制时,如何提供类似CVS中自动增加版本号的功能。作者介绍了Git中的其他版本表示方式,如git describe命令,并提供了使用这些表示方式来确定文件更新情况的示例。此外,文章还介绍了启用$Id:$功能的方法,并讨论了一些开发者在使用Git时的需求和使用场景。 ... [详细]
  • ejava,刘聪dejava
    本文目录一览:1、什么是Java?2、java ... [详细]
  • 像跟踪分布式服务调用那样跟踪Go函数调用链 | Gopher Daily (2020.12.07) ʕ◔ϖ◔ʔ
    每日一谚:“Acacheisjustamemoryleakyouhaven’tmetyet.”—Mr.RogersGo技术专栏“改善Go语⾔编程质量的50个有效实践” ... [详细]
  • React项目中运用React技巧解决实际问题的总结
    本文总结了在React项目中如何运用React技巧解决一些实际问题,包括取消请求和页面卸载的关联,利用useEffect和AbortController等技术实现请求的取消。文章中的代码是简化后的例子,但思想是相通的。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • 如何查询zone下的表的信息
    本文介绍了如何通过TcaplusDB知识库查询zone下的表的信息。包括请求地址、GET请求参数说明、返回参数说明等内容。通过curl方法发起请求,并提供了请求示例。 ... [详细]
author-avatar
花逝留香人走荼茶凉_442
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有