github.com/erda-project/erda-infra@v1.0.9/providers/zookeeper/examples/main.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package main 16 17 import ( 18 "context" 19 "fmt" 20 "os" 21 22 "github.com/erda-project/erda-infra/base/servicehub" 23 "github.com/erda-project/erda-infra/providers/zookeeper" 24 ) 25 26 type provider struct { 27 ZooK zookeeper.Interface // autowired 28 } 29 30 func (p *provider) Run(ctx context.Context) error { 31 conn, ch, err := p.ZooK.Connect() 32 if err != nil { 33 return err 34 } 35 defer conn.Close() 36 for { 37 select { 38 case event := <-ch: 39 // do something 40 fmt.Println(event) 41 case <-ctx.Done(): 42 return nil 43 } 44 } 45 } 46 47 func init() { 48 servicehub.Register("example", &servicehub.Spec{ 49 Services: []string{"example"}, 50 Dependencies: []string{"zookeeper"}, 51 Description: "example", 52 Creator: func() servicehub.Provider { 53 return &provider{} 54 }, 55 }) 56 } 57 58 func main() { 59 hub := servicehub.New() 60 hub.Run("examples", "", os.Args...) 61 } 62 63 // OUTPUT: 64 // INFO[2021-03-18 15:33:03.721] provider zookeeper initialized 65 // INFO[2021-03-18 15:33:03.721] provider example (depends [zookeeper]) initialized 66 // INFO[2021-03-18 15:33:03.721] signals to quit:[hangup interrupt terminated quit] 67 // {EventSession StateConnecting <nil> 127.0.0.1:2181} 68 // 2021/03/18 15:33:04 connected to 127.0.0.1:2181 69 // {EventSession StateConnected <nil> 127.0.0.1:2181} 70 // 2021/03/18 15:33:04 authenticated: id=105855796925956125, timeout=12000 71 // {EventSession StateHasSession <nil> 127.0.0.1:2181} 72 // 2021/03/18 15:33:04 re-submitting `0` credentials after reconnect 73 // ^C 74 // 2021/03/18 15:33:09 recv loop terminated: EOF 75 // 2021/03/18 15:33:09 send loop terminated: <nil> 76 // INFO[2021-03-18 15:33:09.306] provider example exit