Home > Backend Development > Golang > Application practice of go-zero and RabbitMQ

Application practice of go-zero and RabbitMQ

PHPz
Release: 2023-06-23 12:54:10
Original
1469 people have browsed it

Now more and more enterprises are beginning to adopt the microservice architecture model, and in this architecture, message queue has become an important communication method, among which RabbitMQ is widely used. In the Go language, go-zero is a framework that has emerged in recent years. It provides many practical tools and methods to allow developers to use message queues more easily. Below we will introduce go-zero based on practical applications. And the usage and application practice of RabbitMQ.

1. Overview of RabbitMQ

RabbitMQ is an open source, reliable, and efficient message queue software. It is widely used in enterprise-level applications, greatly improving the scalability of application systems. and stability. RabbitMQ uses the AMQP protocol, which is a specification that defines operation messages, which enables different applications to exchange information without language restrictions.

There are four concepts in RabbitMQ: producers, consumers, queues and switches. The producer is the sender of messages, the consumer is the receiver of messages, the queue is the storage container of messages, and the switch is the center of message routing, routing messages to the corresponding queue.

2. Introduction to go-zero

go-zero is a microservice framework based on go language. It provides many practical tools and methods to make it easier for developers to Design and develop high-performance, high-reliability microservices applications. The go-zero framework adopts lightweight design principles to simplify the development process and improve development efficiency.

The message queue module in go-zero uses RabbitMQ, which provides complete message queue support, including producers, consumers, queues and switches, etc., allowing developers to quickly and easily use RabbitMQ for messaging communication. At the same time, go-zero also provides its own logging function, which can effectively track and analyze system operation.

3. How to use go-zero and RabbitMQ

Below we will introduce the use of go-zero and RabbitMQ based on actual cases. This case is a simple user registration and login system. . When a user registers, the system will store the user information in the database and send the message to RabbitMQ at the same time, which will eventually be handed over to the consumer for processing. The consumer is responsible for storing user information in Redis to improve system performance.

3.1 Producer

We first define a user information structure to store user registration information.

type User struct {
    Name     string `json:"name"`
    Password string `json:"password"`
    Email    string `json:"email"`
}
Copy after login

Then, we define a producer interface for sending user information to RabbitMQ.

type Producer interface {
    Publish(ctx context.Context, data []byte) error
}
Copy after login

We use the RabbitMQ implementation in the "go-zero/messaging" library to implement the producer interface. The specific code is as follows.

import (
    "context"
    "encoding/json"
    "time"

    "github.com/gomodule/redigo/redis"
    "github.com/tal-tech/go-zero/core/logx"
    "github.com/tal-tech/go-zero/core/stores/cache"
    "github.com/tal-tech/go-zero/core/stores/redis/redisc"
    "github.com/tal-tech/go-zero/messaging"
    "github.com/tal-tech/go-zero/messaging/rabbitmq"
)

type mqProducer struct {
    publisher messaging.Publisher
    cache     cache.Cache
}

func NewMqProducer(amqpUrl, queueName, exchangeName string) Producer {
    pub := rabbitmq.NewPublisher(amqpUrl, rabbitmq.ExchangeOption(exchangeName))
    cacheConn := redisc.MustNewCache("localhost:6379", "")
    return &mqProducer{
        publisher: pub,
        cache:     cache.NewCache(cacheConn),
    }
}

func (producer *mqProducer) Publish(ctx context.Context, data []byte) error {
    defer producer.cache.Close()
    user := new(User)
    err := json.Unmarshal(data, &user)
    if err != nil {
        return err
    }
    err = producer.cache.Remember(user.Name, func() (interface{}, error) {
        return user, time.Second*3600
    })
    if err != nil {
        logx.Errorf("[Producer]remember cache first:%s", err.Error())
        return err
    }
    return producer.publisher.Publish(ctx, messaging.Message{
        Topic: producer.publisher.GetExchange() + "." + producer.publisher.GetQueue(),
        Body:  data,
    })
}
Copy after login

We use the Redis and Cache modules in the "go-zero/stores" library to store user information in Redis and cache user information in Cache. At the same time, we use the RabbitMQ implementation in the "go-zero/messaging" library to send user information to RabbitMQ. The "NewMqProducer" function is used to create a producer instance, where "amqpUrl" is the connection URL of RabbitMQ, "queueName" is the name of the message queue, and "exchangeName" is the name of the switch. The "Publish" function is used to send user information to RabbitMQ.

3.2 Consumer

Next, we define a consumer interface to receive messages from RabbitMQ and store the messages in Redis.

type Consumer interface {
    Consume(ctx context.Context, handler Handler) error
}

type Handler func(data []byte) error
Copy after login

We use the RabbitMQ implementation in the "go-zero/messaging" library to implement the consumer interface. The specific code is as follows.

type mqConsumer struct {
    consumer messaging.Consumer
    cache    cache.Cache
}

func NewMqConsumer(amqpUrl, queueName, exchangeName, routingKey string) (Consumer, error) {
    sub := rabbitmq.NewSubscriber(amqpUrl, rabbitmq.ExchangeOption(exchangeName))
    err := sub.Subscribe(context.Background(), "", func(msg messaging.Message) error {
        cacheConn := redisc.MustNewCache("localhost:6379", "")
        defer cacheConn.Close()
        user := new(User)
        err := json.Unmarshal(msg.Body, &user)
        if err != nil {
            return err
        }
        err = cacheConn.Remember(user.Name, func() (interface{}, error) {
            return user, time.Second*3600
        })
        if err != nil {
            logx.Errorf("[Consumer]remember cache:%s", err.Error())
            return err
        }
        return nil
    }, rabbitmq.QueueOption(queueName), rabbitmq.QueueDurable())
    if err != nil {
        return nil, err
    }
    return &mqConsumer{
        consumer: sub,
        cache:    cache.NewCache(redisc.MustNewCache("localhost:6379", "")),
    }, nil
}

func (consumer *mqConsumer) Consume(ctx context.Context, handler Handler) error {
    return consumer.consumer.StartConsuming(ctx, func(msg messaging.Message) error {
        return handler(msg.Body)
    })
}
Copy after login

We use the Redis and Cache modules in the "go-zero/stores" library to store user information in Redis. At the same time, we use the RabbitMQ implementation in the "go-zero/messaging" library to receive messages from RabbitMQ. The "NewMqConsumer" function is used to create a consumer instance, where "amqpUrl" is the connection URL of RabbitMQ, "queueName" is the name of the message queue, "exchangeName" is the name of the switch, and "routingKey" is the routing key, used to route messages to the specified queue. The "Consume" function is used to receive messages from RabbitMQ and send the messages to the message processing function "handler".

4. Summary

In this article, we introduce the usage and application practices of go-zero and RabbitMQ based on specific application examples. go-zero provides complete message queue support and can quickly and easily use RabbitMQ for message communication. At the same time, the Redis and Cache modules in the "go-zero/stores" library are used to improve the performance of the system to a new level. With the gradual popularity and application of go-zero, I believe that more and more enterprises and developers will use go-zero and RabbitMQ to build high-performance, high-reliability microservice applications.

The above is the detailed content of Application practice of go-zero and RabbitMQ. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template