package Docker import ( "AudioPlayer/Common" "context" "fmt" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "go-micro.dev/v5/registry" "hash/crc32" "strings" "time" ) type DockerInfo struct { IdName string ContainerId string } func (o *DockerInfo) Exists(dockerClient *client.Client) bool { containerInfo, err := dockerClient.ContainerInspect(context.Background(), o.ContainerId) if err != nil { return false } return containerInfo.State.Running } var onlineContainer map[string]DockerInfo func task() { cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { return } // 查看正在运行的容器 containers, err := cli.ContainerList(context.Background(), container.ListOptions{}) if err != nil { return } for _, summary := range containers { var keysToDelete []string for _, info := range onlineContainer { if info.Exists(cli) { continue } // 读取文件并解析json err = Common.Micro.Deregister(®istry.Service{ Name: "omat_business", Version: "latest", Nodes: []*registry.Node{ { Id: info.IdName, }, }, }) keysToDelete = append(keysToDelete, info.ContainerId) } for _, key := range keysToDelete { delete(onlineContainer, key) } if _, ok := onlineContainer[summary.ID]; ok { continue } if strings.Contains(summary.Image, "business-go") { // 读取文件并解析json err = Common.Micro.Register(®istry.Service{ Name: "omat_business", Version: "latest", Nodes: []*registry.Node{ { Id: fmt.Sprintf("%s-%v", Common.Machine, crc32.ChecksumIEEE([]byte(summary.Image))), Address: "0.0.0.0:443", Metadata: map[string]string{ "protocol": "https", "ip": strings.Join(Common.Address, ","), }, }, }, }) if err != nil { continue } onlineContainer[summary.ID] = DockerInfo{ IdName: fmt.Sprintf("%s-%v", Common.Machine, crc32.ChecksumIEEE([]byte(summary.Image))), ContainerId: summary.ID, } } } } func Start() { onlineContainer = make(map[string]DockerInfo) for { task() time.Sleep(time.Second * 5) } }