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

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

RabbitMQController.cs

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 });
            }
        }
    }
}
相关推荐
自由的好好干活3 小时前
使用Qoder编写ztdaq的C#跨平台示例总结
linux·windows·c#·qoder
FuckPatience3 小时前
C# 实现元素索引由1开始的链表
开发语言·链表·c#
我是唐青枫7 小时前
C#.NET 范围与索引(Range、Index)完全解析:语法、用法与最佳实践
c#·.net
烛阴9 小时前
从`new()`到`.DoSomething()`:一篇讲透C#方法与构造函数的终极指南
前端·c#
深海潜水员10 小时前
【MonoGame游戏开发】| 牧场物语实现 第一卷 : 农场基础实现 (下)
vscode·游戏·c#·.net·monogame
合作小小程序员小小店10 小时前
图书管理系统,基于winform+sql sever,开发语言c#,数据库mysql
开发语言·数据库·sql·microsoft·c#
大侠课堂21 小时前
C#经典面试题100道
开发语言·c#
时光追逐者1 天前
Visual Studio 2026 现已正式发布,更快、更智能!
ide·c#·.net·visual studio
周杰伦fans1 天前
C# 正则表达式完全指南
mysql·正则表达式·c#
Triumph++1 天前
电器模C#汇控电子继块驱动(Modbus协议)
c#·visual studio·c#串口通信