Skip to content

Instantly share code, notes, and snippets.

@M0nteCarl0
Created October 18, 2023 18:52
Show Gist options
  • Save M0nteCarl0/0809971614437405dcf4c6206f36823d to your computer and use it in GitHub Desktop.
Save M0nteCarl0/0809971614437405dcf4c6206f36823d to your computer and use it in GitHub Desktop.
golang async message processing
package main
import (
"fmt"
"time"
)
type MessageProcessor struct {
sendChannel chan<- string // Канал для отправки сообщений
receiveChannel <-chan string // Канал для приема сообщений
}
func main() {
// Создаем каналы для отправки и приема сообщений
sendChannel := make(chan string)
receiveChannel := make(chan string)
// Создаем экземпляр структуры MessageProcessor
processor := MessageProcessor{
sendChannel: sendChannel,
receiveChannel: receiveChannel,
}
// Запускаем горутину для асинхронной обработки сообщений
go processor.processMessages()
// Отправляем сообщения в канал отправки
processor.sendChannel <- "Сообщение 1"
processor.sendChannel <- "Сообщение 2"
processor.sendChannel <- "Сообщение 3"
// Ждем некоторое время, чтобы обработчик успел обработать все сообщения
time.Sleep(2 * time.Second)
// Закрываем каналы
close(sendChannel)
close(receiveChannel)
}
func (mp *MessageProcessor) processMessages() {
// Бесконечный цикл для обработки сообщений из канала приема
for message := range mp.receiveChannel {
// Обрабатываем сообщение
fmt.Println("Обработка сообщения:", message)
// Имитируем обработку сообщения
time.Sleep(1 * time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment