github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/extend/emqx/README.md (about) 1 # emqx 2 3 对业内的emqx客户端进行配置化封装,用于简化获取 4 ### 全部配置 5 ```yaml 6 base: 7 emqx: 8 # 是否开启emqx,默认关闭 9 enable: true 10 servers: 11 # 域名格式1 12 - "tcp://{user}:{password}@{host}:{port}" 13 # 域名格式2 14 - "tcp://{host}:{port}" 15 client-id: "xxxx" 16 username: "xxxx" 17 password: "xxxx" 18 # 是否清理session,默认为true 19 clean-session: true 20 order: true 21 will-enabled: true 22 will-topic: "xxx-topic" 23 will-qos: 0 24 will-retained: false 25 protocol-version: 0 26 keep-alive: 30 27 ping-timeout: "10s" 28 connect-timeout: "30s" 29 max-reconnect-interval: "10m" 30 auto-reconnect: true 31 connect-retry-interval: "30s" 32 connect-retry: false 33 write-timeout: 0 34 resume-subs: false 35 max-resume-pub-in-flight: 0 36 auto-ack-disabled: false 37 ``` 38 提供封装的 `emqx客户端api` 39 ```go 40 func NewEmqxClient() (mqtt.Client, error) {} 41 ``` 42 #### 示例: 43 ```yaml 44 45 ```yaml 46 base: 47 emqx: 48 enable: true 49 servers: 50 - "tcp://{host}:{port}" 51 client-id: "xxxx" 52 username: "xxxx" 53 password: "xxxx" 54 ``` 55 ```go 56 import ( 57 mqtt "github.com/eclipse/paho.mqtt.golang" 58 "github.com/isyscore/isc-gobase/extend/emqx" 59 ) 60 61 // 消息回调函数 62 var msgHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) { 63 fmt.Printf("TOPIC: %s\n", msg.Topic()) 64 fmt.Printf("MSG: %s\n", msg.Payload()) 65 } 66 67 func TestConnect(t *testing.T) { 68 // 获取emqx的客户端 69 emqxClient, _ := emqx.NewEmqxClient() 70 71 // 订阅主题 72 if token := emqxClient.Subscribe("testtopic/#", 0, msgHandler); token.Wait() && token.Error() != nil { 73 fmt.Println(token.Error()) 74 os.Exit(1) 75 } 76 77 // 发布消息 78 token := emqxClient.Publish("testtopic/1", 0, false, "Hello World") 79 token.Wait() 80 81 time.Sleep(1 * time.Second) 82 83 // 取消订阅 84 if token := emqxClient.Unsubscribe("testtopic/#"); token.Wait() && token.Error() != nil { 85 fmt.Println(token.Error()) 86 os.Exit(1) 87 } 88 89 // 断开连接 90 emqxClient.Disconnect(250) 91 time.Sleep(1 * time.Second) 92 } 93 ```