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 });
            }
        }
    }
}
相关推荐
bugcome_com8 小时前
零基础入门C#:一篇搞懂核心知识点
c#
程序员敲代码吗11 小时前
如何通过命令行启动COMSOL的参数化、批处理和集群扫描
java·c#·bash
缺点内向13 小时前
C#: 告别繁琐!轻松移除Word文档中的文本与图片水印
c#·自动化·word·.net
喵叔哟14 小时前
06-ASPNETCore-WebAPI开发
服务器·后端·c#
2501_9307077814 小时前
使用 C# .NET 从 PowerPoint 演示文稿中提取背景图片
c#·powerpoint·.net
初级代码游戏14 小时前
套路化编程 C# winform 自适应缩放布局
开发语言·c#·winform·自动布局·自动缩放
大空大地202616 小时前
流程控制语句--switch多分支语句使用、while循环语句的使用、do...while语句、for循环
c#
kylezhao201917 小时前
C#序列化与反序列化详细讲解与应用
c#
JQLvopkk17 小时前
C# 实践AI :Visual Studio + VSCode 组合方案
人工智能·c#·visual studio
故事不长丨17 小时前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#