golang go-micro Micro Services Framework 2.3 micro introductory notes to receive and publish news of tools

This section describes micro message subscription and publishing content

Before reading this article you might need the following knowledge base

broker proxy

Need to pass messages between the micro broker services through, go-micro supports http / nats / memory three kinds of broker, which is the default http broker.

Meanwhile, go-micro with a strong form of plug-ins provide several common broker as follows.


$ls

gocloud/  googlepubsub/  grpc/  kafka/  mqtt/  nats/  nsq/  proxy/  rabbitmq/  redis/  snssqs/  sqs/  stan/  stomp/

http

HTTP HTTP is based on asynchronous Broker Broker, source code github.com\micro\[email protected]\broker\broker.go, the default is http DefaultBroker


var (
    DefaultBroker Broker = newHttpBroker()
)

httpbroker is actually a structure


type httpBroker struct {

    id      string  //微服务ID
    address string //主机地址
    opts    Options //一些配置
    mux *http.ServeMux  //通过这个监听其他端发送的http请求
    c *http.Client  //通过这个发送请求到其他端
    r registry.Registry 
    sync.RWMutex
    subscribers map[string][]*httpSubscriber  //订阅
    running     bool
    exit        chan chan error
    // offline message inbox
    mtx   sync.RWMutex 
    inbox map[string][][]byte   //数据缓存

}

By http.Clientsending a request, by the http.ServeMuxrealization request listening, by inboxstoring the data

repeat

following initialization code redis


//main.go

//初始化URL格式redis://密码@主机:端口/

b := redis.NewBroker(
        broker.Addrs("redis://user:secret@localhost:6379/"),
        )

//初始化

b.Init()

//连接

b.Connect()

// 新建service

service := grpc.NewService(
        micro.Name("go.micro.web.config"),
        micro.Version("latest"),
        micro.Broker(b),

    )

//初始化service
service.Init()
//启动,运行,监听
service.Run()

Start the application need to specify the broker to redis


go run main.go --broker=redis

grpc initialization

Initialization process is as follows


//main.go

import (
    "github.com/micro/go-plugins/broker/grpc"
)



// 建立连接

b := grpc.NewBroker()
b.Init()
b.Connect()

// 订阅事件
sub, _ := b.Subscribe("events")
defer sub.Unsubscribe()

// 发布事件
b.Publish("events", &broker.Message{

    Headers: map[string]string{"type": "event"},

    Body: []byte(`an event`),

})

Start the application need to specify the broker to grpc


go run main.go --broker=grpc

rabbitmq initialization

Initialization process is as follows


//main.go

import (

    "github.com/micro/go-plugins/broker/grpc"

)

b := rabbitmq.NewBroker(

        broker.Addrs("amqp://用户名:密码@主机host:端口port"),

    )



    b.Init()

    b.Connect()

Start the application need to specify the broker to rabbitmq


go run main.go plugin.go --broker=rabbitmq

mqtt

Initialization process is as follows


//main.go

import (

    "github.com/micro/go-micro"

    "github.com/micro/go-plugins/broker/mqtt"

)

func main() {

    service := micro.NewService(

        micro.Name("my.service"),

        micro.Broker(mqtt.NewBroker()),

    )

    //...

}

Start the application need to specify the broker to mqtt


go run main.go plugin.go --broker=mqtt

other

Other codes can be read


$GOPATH/src/github.com/micro/go-plugins/broker

Publish and subscribe messaging

Subscribe to implement the message through micro.RegisterSubscriber

The main message subscription API interface as the first parameter identifies the subject of a message, the second parameter indicates that the service instance.


// Register Struct as Subscriber

micro.RegisterSubscriber("go.micro.srv.testsrv", service.Server(), new(subscriber.Testsrv))

// Register Function as Subscriber

micro.RegisterSubscriber("go.micro.srv.testsrv", service.Server(), subscriber.Handler)

Important to note that the third parameter, the third parameter is the handler can be a function, it can be achieved

func Handler(ctx context.Context, msg *testsrv.Message) errorThe method of the structure, the internal micro automatically adapted according to the type of parameter. Structure may be implemented in a plurality of func Handler(ctx context.Context, msg *testsrv.Message) errortypes of methods

Subscribe achieved by broker.Subscribe

Broker provides the following interfaces


type Broker interface {

    Init(...Option) error

    Options() Options

    Address() string

    Connect() error

    Disconnect() error

    Publish(topic string, m *Message, opts ...PublishOption) error

    Subscribe(topic string, h Handler, opts ...SubscribeOption) (Subscriber, error)

    String() string

}
  • Subscribe Subscribe to the event, topic behalf of the subject, h event handler

  • Publish publishing events

Handler defined message handler

In the above relates to the handler handler, explained as follows


type Handler func(Event) error

// Event is given to a subscription handler for processing

type Event interface {

    Topic() string

    Message() *Message

    Ack() error

}



type Message struct {

    Header map[string]string

    Body   []byte

}

Published achieved by broker.Publish

For example as follows


// 建立连接

b := grpc.NewBroker()

b.Init()

b.Connect()
// 订阅事件

sub, _ := b.Subscribe("events")

defer sub.Unsubscribe()

// 发布事件

b.Publish("events", &broker.Message{

    Headers: map[string]string{"type": "event"},

    Body: []byte(`an event`),

})

Posted micro publish implemented by

For example as follows


micro publish "go.micro.web.config" "hello"

Combat and code

effect

Download the code broker.zipto extract techidea8.com/microapp/brokerthe next run, the effect of FIG nervous
effect

  • Note announced json format string
 micro publish go.micro.srv.broker "{\"say\":\"这是测试消息\"}"

Get Code

No reply to public attention micro-brokercan be obtained
No public betaidea

Recommended Reading

Sweep micro-channel two-dimensional code to achieve the landing site address provided experience and source code

Language open source project golang go backstage management framework restgo-admin

Support touch gestures, you can slide around the calendar plugin

You have to know 18 Internet business model

Guess you like

Origin www.cnblogs.com/techidea8/p/11430375.html