net8.0一键创建支持(RabbitMQ)

发布于:2025-07-28 ⋅ 阅读:(12) ⋅ 点赞:(0)

Necore项目生成器 - 在线创建Necore模板项目 | 一键下载

 RabbitMQController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Threading.Tasks;
using UnT.Template.Application.Responses;
using UnT.Template.Domain;

namespace UnT.Template.Controllers
{
    [Route("api/rabbimqs")]
    [ApiController]
    public class RabbitMQController : ControllerBase
    {
        private readonly ConnectionFactory _connectionFactory;

        public RabbitMQController(ConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
        }

        [HttpPost("publish")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
        public async Task<IActionResult> Insert()
        {
            try
            {
                using (var connection = await _connectionFactory.CreateConnectionAsync())
                using (var channel = await connection.CreateChannelAsync())
                {
                    await channel.QueueDeclareAsync(queue: "unt_queue",
                    durable: true,
                    exclusive: false,
                    autoDelete: false,
                    arguments: null);

                    await channel.BasicPublishAsync(exchange: "",
                                         routingKey: "unt_queue",
                                         mandatory: false,
                                         body: System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(new Pro_Product { Name = DateTime.Now.ToFileTime().ToString() })));
                }
                return Ok(new ApiResponse<bool> { Success = true, Data = true });
            }
            catch (Exception ex)
            {
                return Ok(new ApiResponse<bool> { Success = false, Message = ex.Message, Data = false });
            }
        }

        [HttpPost("consume")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ApiResponse<bool>), StatusCodes.Status200OK)]
        public async Task<IActionResult> Consume()
        {
            try
            {
                Task.Run(() =>
                {
                    var connection = _connectionFactory.CreateConnectionAsync().GetAwaiter().GetResult();
                    var channel = connection.CreateChannelAsync().GetAwaiter().GetResult();
                    {
                        // 创建消费者
                        var consumer = new AsyncEventingBasicConsumer(channel);
                        channel.BasicConsumeAsync(queue: "unt_queue",
                       autoAck: false,
                       consumer: consumer).GetAwaiter().GetResult();
                        // 注册接收事件处理程序
                        consumer.ReceivedAsync += async (model, ea) =>
                        {
                            var body = ea.Body.ToArray();
                            var message = Encoding.UTF8.GetString(body);
                            Console.WriteLine($" [x] Received {message}");
                            // 手动确认消息(如果autoAck=false)
                            channel.BasicAckAsync(ea.DeliveryTag, false).ConfigureAwait(false).GetAwaiter().GetResult();
                        };
                    }

                });
                await Task.Delay(TimeSpan.FromSeconds(5));
                return Ok(new ApiResponse<bool> { Success = true, Data = true });
            }
            catch (Exception ex)
            {
                return Ok(new ApiResponse<bool> { Success = false, Message = ex.Message, Data = false });
            }
        }
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到