RabbitMQ是以Erlang所編寫的Message broker, 支援的語言相當的廣泛。Spring boot/cloud跟Steeltoe的Message broker也是使用Rabbit MQ,來寫個小小的練習體驗一下非同步通訊跟技術異質性,使用Web API來call另一個Console專案的服務
依據RabbitMQ官網的指示在windows跟專案安裝完RabbitMQ跟相關的nuget套件後,
首先加入一個web api controller名為SayHelloController
然後在RabbitMQ的部分,先建立起connection --> 建立channel-->設定Queue的名字-->publish message
using System.Text;
using Microsoft.AspNetCore.Mvc;
using RabbitMQ.Client;
namespace APIGateway.Controllers
{
[Produces("application/json")]
[Route("api/SayHello")]
public class SayHelloController : Controller
{
// POST: api/SayHello
[HttpPost]
public string Post([FromQuery]string name)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection()) {
using (var channel = connection.CreateModel()) {
channel.QueueDeclare(
queue: "hello",
exclusive: false,
autoDelete: false,
arguments: null
);
string message = name;
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(
exchange: "",
routingKey: "hello", basicProperties: null,
body: body);
}
}
return $"Hello,{name}";
}
}
}
加入一個新的Console專案,名為SayHelloService
在Program.cs裡面 編寫consumer相關的代碼
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
namespace SayHelloService
{
class Program
{
static void Main(string[] args) {
SubscribeToAPIGateway();
}
private static void SubscribeToAPIGateway() {
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel()) {
channel.QueueDeclare(
queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine($"Received: {message}");
Console.WriteLine($"Hello, {message}");
};
channel.BasicConsume(
queue: "hello",
autoAck: true,
consumer: consumer);
Console.WriteLine("Pess any key to exit");
Console.ReadLine();
}
}
}
}
補充一點是channel.BasicConsume中的參數將autoAck設為true,RabbitMQ才會將consumer接到的該消息從queue移除。
啟用API gateway的服務後,啟用SayHelloService服務
在browser的網址輸入 http://localhost:{API_Gateway_port}/api/SayHello?name=John
會看到SayHelloService的console印出 Hello, John
ps:看RabbitMQ的文件花掉好多時間,光是RabbitMQ就好多東西了,本來還想試著用RabbitMQ取代之前用的restful wpi來做service registry。