我应该如何使用带有protobuf-net的Booksleeve?

Dav*_*ler 3 protobuf-net redis booksleeve

我使用RedisConnection Set方法设置字节数组但是如何获取数据?get返回一个包装的字节数组?

链接:

这有效,但感觉不对:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BookSleeve;
using ProtoBuf;
using System.IO;
namespace RedisTest001
{
    [ProtoContract, Serializable]
    public class Price
    {
        private string _ticker;
        private double _value;

        public Price()
        {
        }

        public Price(string ticker, double value)
        {
            _ticker = ticker;
            _value = value;
        }


        [ProtoMember(1)]
        public string Ticker
        {
            get { return _ticker; }
            set { _ticker = value; }
        }

        [ProtoMember(2)]
        public double Value
        {
            get { return _value; }
            set { _value = value; }
        }


    }

    class Program
    {
        static void Main(string[] args)
        {
            using (var conn = new RedisConnection("localhost"))
            {
                Price p = new Price("IBM", 101.55);

                byte[] raw;
                using (MemoryStream ms = new MemoryStream())
                {
                    Serializer.Serialize<Price>(ms,p);
                    raw = ms.ToArray();
                }

                conn.Open();
                conn.Set(1, p.Ticker, raw);


                var tb  = conn.Get(1,"IBM");

                var str = conn.Wait(tb);

                 Price p2 = Serializer.Deserialize<Price>(new MemoryStream(str));

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更多信息:

public static class pex
{
    public static byte[] ToBArray<T>(this T o)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            Serializer.Serialize<T>(ms, o);
            return ms.ToArray();
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Random RandomClass = new Random();

        using (var conn = new RedisConnection("localhost"))
        {

            conn.Open();

            for (int i = 0; i < 500000; i++)
            {
                Price p = new Price("IBM", RandomClass.Next(0, 1000));
                conn.AddToSet(2, "PRICE.IBM", p.ToBArray());
            }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 11

这是完全正确的."Get"(BookSleeve)返回延迟byte[].你已经正确地使用Wait来获取实际值byte[],然后使用MemoryStreamover byte[]Deserialize通过protobuf-net 调用.

都好.

如果你说清楚任何你觉得难看的步骤,我可能会更具体,但是:

  • BookSleeve完全是异步通过Task,因此需要任何一个WaitContinueWith访问byte[]
  • protobuf-net完全基于流,因此需要MemoryStream坐在上面byte[]

当然,如果添加通用实用程序方法(可能是扩展方法),则只需编写一次.

如果有一个包装类(用于某些跟踪/滑动到期)和一个L1高速缓存(Redis为L2),那么我们在stackoverflow中使用它的方式非常严格.

一个注意事项:连接是线程安全的,旨在大规模共享; 每次操作都不要连接.

  • @MarcGravell:您建议不要对每个操作进行连接.那么推荐的模式是什么?使用单例来创建和提供一个连接对象?并且:如果网络连接中断,会发生什么?我应该捕获网络异常并重新创建(单例)连接对象吗? (2认同)