0

我创建了以下单例类来处理 Redis 连接,并公开 BookSleeve 功能:

public class RedisConnection
{
    private static RedisConnection _instance = null;
    private BookSleeve.RedisSubscriberConnection _channel;
    private readonly int _db;
    private readonly string[] _keys;                        // represent channel name


    public BookSleeve.RedisConnection _connection;


    /// <summary>
    /// Initialize all class parameters
    /// </summary>
    private RedisConnection(string serverList, int db, IEnumerable<string> keys) 
    {
        _connection = ConnectionUtils.Connect(serverList);
        _db = db;
        _keys = keys.ToArray();

        _connection.Closed += OnConnectionClosed;
        _connection.Error += OnConnectionError;

        // Create a subscription channel in redis
        _channel = _connection.GetOpenSubscriberChannel();

        // Subscribe to the registered connections
        _channel.Subscribe(_keys, OnMessage);

        // Dirty hack but it seems like subscribe returns before the actual
        // subscription is properly setup in some cases
        while (_channel.SubscriptionCount == 0)
        {
            Thread.Sleep(500);
        }
    }

    /// <summary>
    /// Do something when a message is received
    /// </summary>
    /// <param name="key"></param>
    /// <param name="data"></param>
    private void OnMessage(string key, byte[] data)
    {
        // since we are just interested in pub/sub, no data persistence is active
        // however, if the persistence flag is enabled, here is where we can save the data

        // The key is the stream id (channel)
        //var message = RedisMessage.Deserialize(data);
        var message = Helpers.BytesToString(data);

        if (true) ;

        //_publishQueue.Enqueue(() => OnReceived(key, (ulong)message.Id, message.Messages));
    }

    public static RedisConnection GetInstance(string serverList, int db, IEnumerable<string> keys) 
    {
        if (_instance == null)
        {
            // could include some sort of lock for thread safety
            _instance = new RedisConnection(serverList, db, keys);
        }

        return _instance;
    }



    private static void OnConnectionClosed(object sender, EventArgs e)
    {
        // Should we auto reconnect?
        if (true)
        {
            ;
        }
    }

    private static void OnConnectionError(object sender, BookSleeve.ErrorEventArgs e)
    {
        // How do we bubble errors?
        if (true)
        {
            ;
        }
    }
}

由于以下错误,在OnMessage(),var message = RedisMessage.Deserialize(data);中被注释掉:

RedisMessage 由于其保护级别而无法访问。

RedisMessage 是 BookSleeve 中的一个抽象类,我有点不明白为什么我不能使用它。

我遇到了这个问题,因为当我向通道 (pub/sub) 发送消息时,我可能想在 OnMessage() 中对它们做一些事情——例如,如果设置了持久性标志,我可能会选择开始记录数据。问题是此时数据已序列化,我希望将其反序列化(为字符串)并将其保存在 Redis 中。

这是我的测试方法:

    [TestMethod]
    public void TestRedisConnection()
    {
        // setup parameters
        string serverList = "dbcache1.local:6379";
        int db = 0;

        List<string> eventKeys = new List<string>();
        eventKeys.Add("Testing.FaucetChannel");

        BookSleeve.RedisConnection redisConnection = Faucet.Services.RedisConnection.GetInstance(serverList, db, eventKeys)._connection;

        // broadcast to a channel
        redisConnection.Publish("Testing.FaucetChannel", "a published value!!!");

    }

由于我无法使用该Deserialize()方法,因此我创建了一个静态帮助器类:

public static class Helpers
{
    /// <summary>
    /// Serializes a string to bytes
    /// </summary>
    /// <param name="val"></param>
    /// <returns></returns>
    public static byte[] StringToBytes(string str)
    {
        try
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }
        catch (Exception ex) 
        { 
            /* handle exception omitted */
            return null;
        }
    }


    /// <summary>
    /// Deserializes bytes to string
    /// </summary>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public static string BytesToString(byte[] bytes)
    {
        string set;
        try
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }
        catch (Exception ex)
        {
            // removed error handling logic!
            return null;
        }
    }


}

不幸的是,这没有正确地将字符串反序列化回其原始形式,我得到的是这样的:⁡异汢獩敨⁤庆畲㩥ㄠ,而不是实际的原始文本。

建议?

4

2 回答 2

0

RedisMessage represents a pending request that is about to be sent to the server; there are a few concrete implementations of this, typically relating to the nature and quantity of the parameters to be sent. It makes no sense to "deserialize" (or even "serialize") a RedisMessage - that is not their purpose. The only thing it is sensible to do is to Write(...) them to a Stream.

If you want information about a RedisMessage, then .ToString() has an overview, but this is not round-trippable and is frankly intended for debugging.

RedisMessage is an internal class; an implementation detail. Unless you're working on a pull request to the core code, you should never need to interact with a RedisMessage.

At a similar level, there is RedisResult which represents a response coming back from the server. If you want a quick way of getting data from that, fortunately that is much simpler:

object val = result.Parse(true);

(the true means "speculatively test to see if the data looks like a string"). But again, this is an internal implementation detail that you should not have to work with.

于 2013-02-21T15:02:58.067 回答
0

显然这是一个编码类型问题,同时,稍微看一下这个链接,我简单地添加了 UTF8 的编码类型,输出看起来很好:

   #region EncodingType enum
    /// <summary> 
    /// Encoding Types. 
    /// </summary> 
    public enum EncodingType 
{ 
    ASCII, 
    Unicode, 
    UTF7, 
    UTF8 
} 
#endregion 

#region ByteArrayToString 
/// <summary> 
/// Converts a byte array to a string using Unicode encoding. 
/// </summary> 
/// <param name="bytes">Array of bytes to be converted.</param> 
/// <returns>string</returns> 
public static string ByteArrayToString(byte[] bytes) 
{ 
    return ByteArrayToString(bytes, EncodingType.Unicode); 
} 
/// <summary> 
/// Converts a byte array to a string using specified encoding. 
/// </summary> 
/// <param name="bytes">Array of bytes to be converted.</param> 
/// <param name="encodingType">EncodingType enum.</param> 
/// <returns>string</returns> 
public static string ByteArrayToString(byte[] bytes, EncodingType encodingType) 
{ 
    System.Text.Encoding encoding=null; 
    switch (encodingType) 
    { 
        case EncodingType.ASCII: 
            encoding=new System.Text.ASCIIEncoding(); 
            break;    
        case EncodingType.Unicode: 
            encoding=new System.Text.UnicodeEncoding(); 
            break;    
        case EncodingType.UTF7: 
            encoding=new System.Text.UTF7Encoding(); 
            break;    
        case EncodingType.UTF8: 
            encoding=new System.Text.UTF8Encoding(); 
            break;    
    } 
    return encoding.GetString(bytes); 
} 
#endregion

- 更新 -

更简单:var message = Encoding.UTF8.GetString(data);

于 2013-02-20T21:06:28.260 回答