Falcon.SugarApi/RabbitMqTest/RabbitmqBase.cs

63 lines
1.9 KiB
C#

using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RabbitMqTest
{
public abstract class RabbitmqBase
{
/// <summary>
/// 创建通道
/// </summary>
/// <returns></returns>
protected virtual IModel GetChannel() {
var factory = new ConnectionFactory { HostName="localhost" };
var connection = factory.CreateConnection();
return connection.CreateModel();
}
private static string MessageChars = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>''""";
/// <summary>
/// 生成随机消息
/// </summary>
protected virtual string RandomString(int len = 10) {
var random = new Random();
int charslen = MessageChars.Length;
StringBuilder sb = new(len);
for(int i = 0;i<len;i++) {
var ci = random.Next(0,charslen-1);
sb.Append(MessageChars[ci]);
}
return sb.ToString();
}
/// <summary>
/// 生成随机消息字节数组
/// </summary>
/// <param name="len"></param>
/// <returns></returns>
protected virtual Byte[] RandomMsgBytes(int len = 10) {
var str = RandomString(len);
return Encoding.UTF8.GetBytes(str);
}
/// <summary>
/// 创建队列
/// </summary>
protected virtual void QueueDeclare(IModel channel,string queueName) {
channel.QueueDeclare(queueName,exclusive: false);
}
/// <summary>
/// 创建交换机
/// </summary>
protected virtual void ExchangeDeclare(IModel channel,string exchangeName) {
channel.ExchangeDeclare(exchangeName,ExchangeType.Fanout,autoDelete: true);
}
}
}