2016-01-15 110 views
3

我有一個主從配置,有兩個奴隸和三個哨兵。如果我用命令行嘗試命令,一切都可以。 但我有一些問題配置爲C#。 我正在使用StackExchange.Redis庫。但我不明白我應該怎麼做才能從主設備獲取/設置密鑰。我應該手動找到主人,然後獲取或設置密鑰,還是自動執行?什麼是最好的方式來做到這一點?每次我想要得到/設置一個密鑰,我應該檢查誰是主人? 現在我只做了這件事,而我只留下了其他代碼,因爲它只有一個主人。使用來自c的Redis哨兵#

private static string ServiceName = "mymaster"; 
private static string IP { get { return "127.0.0.1"; } } 
private static int Port = 26379; 

public static readonly ConnectionMultiplexer Connection = GetConn(); 
public static readonly IServer Server = Connection.GetServer(IP, Port); 

public static ConnectionMultiplexer GetConn() 
{ 
    try 
    { 
     // create a connection 
     var options = new ConfigurationOptions() 
     { 
      CommandMap = CommandMap.Sentinel, 
      EndPoints = { { IP, Port } }, 
      AllowAdmin = true, 
      TieBreaker = "", 
      ServiceName = ServiceName, 
      SyncTimeout = 5000, 
      AbortOnConnectFail = true, 
      Ssl = false 
     }; 
     var connection = ConnectionMultiplexer.Connect(options, Console.Out); 
     return connection; 
    } 
    catch (Exception ex) 
    { 
     ASLog.LogError(ex, 1); 
     return null; 
    } 
} 

在那裏我有三個哨兵一個在端口26379. 很抱歉,但我有點困惑如何在C#中使用它。

回答

0

您不需要指定或檢查主節點,庫將選擇主設備進行寫操作。

無論如何,所有的方法都有一個可選的CommandFlags參數,您可以指定在哪裏執行操作(DemandMaster,DemandSlave,PreferMaster,PreferSlave)。

例如:

var cnn = ConnectionMultiplexer.Connect("localhost:6379"); 
var db = cnn.GetDatabase(); 
db.StringSet("key", "value", null, When.Always, CommandFlags.DemandMaster); 
var value = db.StringGet("key", CommandFlags.PreferSlave); 
+0

當我嘗試使用'StringSet'它說'這個操作已經在命令地圖被禁用,並且不能使用:SETEX' .. – ayasha

+0

你有什麼['重命名命令'](http://redis.io/topics/security#disabling-of-specific-commands)on redis.conf? – thepirat000

+0

不是..那是什麼? – ayasha