受欢迎的博客标签

1.Can StackExchange.Redis be used to store POCO?

StackExchange.Redis can store Redis Strings, which are binary safe. That means, that you can easily serialize a POCO using the serialization technology of your choice and put it in there.

The following example uses the .NET BinaryFormatter. Please note that you have to decorate your class with the SerializableAttribute to make this work.

Example set operation:

PocoType somePoco = new PocoType
            {
                Id = 1,
                Name = "YouNameIt"
            };
            string key = "myObject1";
            byte[] bytes;
            using (var stream = new MemoryStream())
            {
                new BinaryFormatter().Serialize(stream, somePoco);
                bytes = stream.ToArray();
            }
            db.StringSet(key, bytes);
            Example get operation:
            string key = "myObject1";
            PocoType somePoco = null;
            byte[] bytes = (byte[])db.StringGet(key);
            if (bytes != null)
            {
                using (var stream = new MemoryStream(bytes))
                {
                    somePoco = (PocoType)new BinaryFormatter().Deserialize(stream);
                }
            }

2.How to use Queue in StackExchange.Redis

Redis supports both queues and stacks through the LPUSH, LPOP, RPUSH and RPOP commands. It is just a matter of calling the right operations on a list.

Below are sample implementations of a queue and a stack as a reference.

"Connection" in the code below is just an instance of a ConnectionMultiplexer

 static class RedisStack
    {
        public static void Push(RedisKey stackName, RedisValue value)
        {
            Connection.GetDatabase().ListRightPush(stackName, value);
        }
        public static RedisValue Pop(RedisKey stackName)
        {
            return Connection.GetDatabase().ListRightPop(stackName);
        }
    }
    static class RedisQueue
    {
        public static void Push(RedisKey stackName, RedisValue value)
        {
            Connection.GetDatabase().ListRightPush(stackName, value);
        }
        public static RedisValue Pop(RedisKey stackName)
        {
            return Connection.GetDatabase().ListLeftPop(stackName);
        }
    }