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 });
            }
        }
    }
}
相关推荐
心平气和量大福大7 小时前
C#-WPF-Window主窗体
开发语言·c#·wpf
白露与泡影7 小时前
Arthas 实战指南:从方法耗时定位到 JVM 变量热修改
服务器·jvm·c#
EIP低代码平台12 小时前
EIP低代码平台系统-字典功能讲解
低代码·c#·工作流
吉普赛的歌13 小时前
YARP负载均衡配置了多个相同接口导致的报错
c#·yarp
张人玉14 小时前
C# WinForms——工厂管理系统(C# WinForms)
数据库·sqlite·c#·winform
夜莺悠吟16 小时前
关于对 C# 中 ImplicitUsings,GlobalUsings 的讨论
c#·.net
不正经学生16 小时前
C 语言函数深入剖析(基础篇)—— 从零理解函数的每一个细节
c语言·开发语言·数据结构·算法·c#
-银雾鸢尾-1 天前
C#中的拓展方法
开发语言·c#
EIP低代码平台1 天前
EIP低代码平台-系统参数配置详解|落地三级等保+高灵活私有化部署方案
低代码·c#·权限·工作流·netcore
王莎莎-MinerU1 天前
MCP 解决的是工具接入,科研 Agent 还缺的是科学证据接口标准化
开发语言·网络·人工智能·深度学习·pdf·c#·php