将URI传递给RabbitMQ

时间:2016-04-07 17:55:48

标签: c# rabbitmq

我使用下面的代码连接到RabbitMQ

factory.UserName = "userid";
factory.Password = "mypass@25";
factory.VirtualHost = "/filestream";
factory.Port = AmqpTcpEndpoint.UseDefaultPort;
factory.HostName = "myrabbitserver";
return factory.CreateConnection();

我想将连接设置更改为以下格式:

amqp://userid:mypass@25@myrabbitserver:5672/filestream

我的密码有@个字符,因此我无法传递URI

var factory = new ConnectionFactory();
factory.Uri = "amqp://userid:mypass@25@myrabbitserver:5672/filestream";

我最终手动提供工厂的每个属性。有没有办法让我们通过做类似下面的事情告诉RabbitMQ我的密码是@?

factory.Uri = "amqp://userid:"mypass@25"@myrabbitserver:5672/filestream";

如果我尝试将密码中的@更改为%40,则在获取连接时会抛出错误

None of the specified endpoints were reachable

6 个答案:

答案 0 :(得分:2)

您可以尝试以下操作:-

 string rabbitmqconnection = $"amqp://{HttpUtility.UrlEncode("username")}: 
 {HttpUtility.UrlEncode("password")}@{"hostname"}
 /{HttpUtility.UrlEncode("/vhost")}";

希望这可以解决您的问题。

答案 1 :(得分:1)

显然,无法对密码中的@字符进行编码或转义。我为用户更改了密码,以避免出现此字符,一切都按预期工作。

答案 2 :(得分:0)

您需要URLEncode密码中的符号@

根据你的情况,你可以尝试这个uri:

amqp://userid:mypass%4025@myrabbitserver:5672/filestream

答案 3 :(得分:0)

我能够将本机编码器导入我的代码中:

import java.net.URLEncoder;

然后,对带有特殊字符(包括虚拟主机,因为有'/'字符)的变量运行“ encode”方法:

String un_encoded = URLEncoder.encode(username); 
String pw_encoded = URLEncoder.encode(password); 
String vhost_encoded = URLEncoder.encode(virtualHost);

这样做可以让我在ConnectionFactory工厂对象上运行 setUri 方法。

答案 4 :(得分:-1)

我强烈建议您将兔子连接字符串信息放在数据库连接字符串旁边的web.config或app.config中。然后您可以按如下方式使用它们:

web.config条目

  <connectionStrings>
     <add name="RabbitMQ" connectionString="amqp://{username}:{password}@{server}/{vhost}" />
  </connectionStrings>

C#代码(以Ninject为例)

Bind<IConnection>()
    .ToMethod(ctx =>
                {
var connectionString = configurationManager.ConnectionStrings["RabbitMQ"].ConnectionString;
                    var factory = new ConnectionFactory
                                {
                                    Uri = ConnectionString,
                                    RequestedHeartbeat = 15,
                                    //every N seconds the server will send a heartbeat.  If the connection does not receive a heartbeat within
                                    //N*2 then the connection is considered dead.
                                    //suggested from http://public.hudl.com/bits/archives/2013/11/11/c-rabbitmq-happy-servers/
                                    AutomaticRecoveryEnabled = true
                                };

                    return factory.CreateConnection();
                })
    .InSingletonScope();

当你这样做时,你不需要&#34; 5672 / filestream&#34;在连接字符串中。当您使用&#34; ampq://&#34;

连接字符串时,暗示5672

答案 5 :(得分:-2)

factory.VirtualHost = "/filestream"; //this has char '/' should change to '%2f'

factory.Uri = "amqp://userid:mypass%4025@myrabbitserver:5672/%2ffilestream";