首页 \ 问答 \ Hazelcast,Kryo,JsonNode Serializer(Hazelcast, Kryo, JsonNode Serializer)

Hazelcast,Kryo,JsonNode Serializer(Hazelcast, Kryo, JsonNode Serializer)

我正在使用分布式MAP作为条目实现Hazelcast应用程序。 我的JsonNodeSerializer如下所示

private final ObjectReader jsonNodeReader;
private final ObjectWriter jsonNodeWriter;

@Override
public void write(ObjectDataOutput out, JsonNode jsonNode)
        throws IOException {
    out.write(jsonNodeWriter.writeValueAsBytes(jsonNode));
}

@Override
public JsonNode read(ObjectDataInput in)
        throws IOException {
    return jsonNodeReader.readTree(in);
}

但是,我想使用Kryo来避免使用JsonNodeReader / Writer来节省一些空间并提高性能。

我尝试使用Kryo并且我无法读取JsonNode / ObjectNode,因为我们没有no-args构造函数。

@Override
public void write(ObjectDataOutput out, JsonNode jsonNode)
        throws IOException {
    Kryo kryo = KRYO_THREAD_LOCAL.get();
    Output output = new Output((OutputStream) out);
    kryo.writeObject(output, jsonNode);
    output.flush();

    //out.write(jsonNodeWriter.writeValueAsBytes(jsonNode));
}

@Trace(dispatcher = true)
@Override
public JsonNode read(ObjectDataInput in)
        throws IOException {
    InputStream inputStream = (InputStream) in;
    Input input = new Input(inputStream);
    Kryo kryo = KRYO_THREAD_LOCAL.get();
    return kryo.readObject(input, ObjectNode.class);
   // return jsonNodeReader.readTree(in);
} 

不确定我使用JsonNodeReader / Writer的方法是否最佳或使用Kryo将使我的解决方案更好。

我的目标是节省空间并提高性能。 欢迎任何建议让我朝着正确的方向前进。 谢谢


I am implementing a Hazelcast application using distributed MAP with as the entry. My JsonNodeSerializer looks like as shown below

private final ObjectReader jsonNodeReader;
private final ObjectWriter jsonNodeWriter;

@Override
public void write(ObjectDataOutput out, JsonNode jsonNode)
        throws IOException {
    out.write(jsonNodeWriter.writeValueAsBytes(jsonNode));
}

@Override
public JsonNode read(ObjectDataInput in)
        throws IOException {
    return jsonNodeReader.readTree(in);
}

However, I wanted to use Kryo to avoid using JsonNodeReader/Writer to save some space and improve performance.

I tried using Kryo and I am not able to read JsonNode/ObjectNode as we do not have no-args constructor.

@Override
public void write(ObjectDataOutput out, JsonNode jsonNode)
        throws IOException {
    Kryo kryo = KRYO_THREAD_LOCAL.get();
    Output output = new Output((OutputStream) out);
    kryo.writeObject(output, jsonNode);
    output.flush();

    //out.write(jsonNodeWriter.writeValueAsBytes(jsonNode));
}

@Trace(dispatcher = true)
@Override
public JsonNode read(ObjectDataInput in)
        throws IOException {
    InputStream inputStream = (InputStream) in;
    Input input = new Input(inputStream);
    Kryo kryo = KRYO_THREAD_LOCAL.get();
    return kryo.readObject(input, ObjectNode.class);
   // return jsonNodeReader.readTree(in);
} 

Not sure if my approach to use JsonNodeReader/Writer is optimal or Using Kryo will make my solution better.

My goal is the save space and improve performance. Any suggestions are welcome to put me in right direction. Thanks


原文:https://stackoverflow.com/questions/40099559
更新时间:2022-04-04 20:04

最满意答案

坦率地说,你的JSON结果非常糟糕,框架工具无法帮助你轻松创建它。 回溯并考虑这样的JSON结构,而不是在同一列表中混合使用不同类型的数据:

{
    "titles": ["title_1", "title_2", "title_3"]
    "books": [
        {
            "id": 62,
            "category_url": "http://127.0.0.1:8000/categories/just-because/",
            "slug": "XG84Jberu6",
        },
        {
            "id": 63,
            "category_url": "http://127.0.0.1:8000/categories/something/",
            "slug": "YU65Zirvq7",
        }
    ]
}

从简单的api_view返回:

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view()
def combined_view(request):
    obj1 = Books.objects.most_read_offset()[:30]
    titles = Category.objects.most_publishes().values_list('title', flat=True)
    books_serializer = BookSerializer(obj1, context={'request': request}, many=True)  # this is your previous serializer
    return Response({
        "titles": titles,
        "books": books_serializer.data,
    })

如果您的most_read_offset()不包含most_read_offset() select_related('category') ,则应该添加此内容,因为您在get_category_url获取所有书对象的get_category_url


Your JSON result has, quite frankly, a terrible structure and the framework tools will not help you create it easily. Back-track and consider a JSON structure like this instead where you don't mix different kinds of data in the same list:

{
    "titles": ["title_1", "title_2", "title_3"]
    "books": [
        {
            "id": 62,
            "category_url": "http://127.0.0.1:8000/categories/just-because/",
            "slug": "XG84Jberu6",
        },
        {
            "id": 63,
            "category_url": "http://127.0.0.1:8000/categories/something/",
            "slug": "YU65Zirvq7",
        }
    ]
}

And return this from a simple api_view:

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view()
def combined_view(request):
    obj1 = Books.objects.most_read_offset()[:30]
    titles = Category.objects.most_publishes().values_list('title', flat=True)
    books_serializer = BookSerializer(obj1, context={'request': request}, many=True)  # this is your previous serializer
    return Response({
        "titles": titles,
        "books": books_serializer.data,
    })

If your most_read_offset() queryset doesn't include a select_related('category') you should add this as well since your fetching the category for all book objects in get_category_url.

相关问答

更多
  • 至于为什么你的代码会引发一个错误:你必须使用my_list.append(number) ( my_list += anything都是my_list.extends(anything)的快捷方式,它需要一个iterable并将这个迭代中的所有值附加到my_list )。 实际上,这里的pythonic方式是使用列表推导,即: my_list = [foo.id for foo in bar] 但由于它是关于Django查询集,正确的解决方案是使用QuerySet.values_list() : bar ...
  • only()指定应从数据库填充哪些字段,但不会阻止访问模型上的其他字段。 如果要限制结果对象中可用的字段,则应使用values()或values_list() 。 请注意,它们都不返回模型,因为使用模型仍会使其他字段可用。 only() specifies which fields should be populated from the database, but it does not prevent other fields on the model from being accessed. If y ...
  • 您正在函数get_context_data中使用变量media ,但您没有在函数中定义变量。 Python变量绑定在函数范围内,因此如果不先定义它,就不能使用它。 您不应该在函数get_queryset查询media ,因为get_queryset旨在获取ListView将在模板中迭代的查询集,因此它应该只返回一个结果。 如果你想要额外的上下文,可以在函数get_context_data : def get_context_data(self, **kwargs): context = super( ...
  • 这应该可能工作 更改 data=[i.num_avg for i in my_query] 至 data=[i['num_avg'] for i in my_query] This should probably work Change data=[i.num_avg for i in my_query] to data=[i['num_avg'] for i in my_query]
  • 我假设你需要['2009年6月','2009年8月','2009年9月','2010年1月]在你的模板中显示。 如果是这样,那么你可以做类似的事情 Article.objects.values_list('date_added', flat=True) 这会给你一个这些日期的列表。 然后,您可以使用date模板过滤器输出您想要的内容。 就像是 {% for item in your_dates_list_that_you_passed_to_the_template %} {{ item|date: ...
  • 正如错误描述,你不能返回一个jsonresponse。 而是返回上下文。 例如 from django.http import JsonResponse def different_function_name(request, *args, **kwargs): if kwargs.get('pk', None): q = kwargs.get('pk', None) queryset = Reports.objects.all().values('id','line_ ...
  • 根据你的情况( 这次是一个简单的查询 ),你有很多选择。 一种是使用变量作为字段名称。 然后,动态地提供该变量: >>> field='headline' >>> Entry.objects.values_list(field, flat=True).get(pk=1) 'First entry' >>> field='body' >>> Entry.objects.values_list(field, flat=True).get(pk=1) 'First entry body' 为了分割结果,使用偏 ...
  • 你需要解压缩值:) def get_values(self, *fields): return MyModel.objects.values(*fields) # note the * 否则就像你写的那样 def get_values(self, *fields): return MyModel.objects.values(('field1', 'field2')) # note the extra () ...因此AttributeError: 'tuple' object ha ...
  • 坦率地说,你的JSON结果非常糟糕,框架工具无法帮助你轻松创建它。 回溯并考虑这样的JSON结构,而不是在同一列表中混合使用不同类型的数据: { "titles": ["title_1", "title_2", "title_3"] "books": [ { "id": 62, "category_url": "http://127.0.0.1:8000/categories/just-because/", ...
  • 通过运行for循环,您可以执行Django调用的对QuerySet 评估的操作。 在此之前,它被认为是懒惰的 ,这意味着添加过滤器和其他QuerySet方法实际上并没有命中数据库。 QuerySets的一个有趣片段是懒惰的 (也见那里的例子): QuerySets是惰性的 - 创建QuerySet的行为不涉及任何数据库活动。 您可以整天将过滤器堆叠在一起,在评估QuerySet之前,Django实际上不会运行查询。 有一些用于评估QuerySet语句和方法,这些语句和方法在评估QuerySet记录,包括迭代 ...

相关文章

更多

最新问答

更多
  • 使用通配符获取更多servlet请求变量[重复](Get more servlet request variables using wildcards [duplicate])
  • 返回相同的集合类型,参数化不同(Returning same collection type, differently parameterised)
  • C ++朋友函数模板重载和SFINAE在clang ++,g ++,vc ++中的不同行为(C ++ 14模式)(C++ friend function template overloading and SFINAE different behaviors in clang++, g++, vc++ (C++14 mode))
  • 与paure IoT-Hub的Python paho-MQTT连接(Python paho-MQTT connection with azure IoT-Hub)
  • 编译器警告“来自不同的Objective-C类型的赋值”(Compiler warning “assignment from distinct objective-c type”)
  • C ++编译错误(在此函数中未初始化)[重复](C++ Compile Error (uninitialized in this function) [duplicate])
  • unsigned-signed下溢机制(unsigned-signed underflow mechanism)
  • 快速行查询的数据结构?(Data structure for fast line queries?)
  • 饥荒有手机安卓版的吗
  • Jquery可拖动碰撞检测错误(Jquery draggable collision detection bug)
  • sql调优是怎样来实现的?
  • 无法使占位符输入文本消失(Unable to make the placeholder input text disappear)
  • jQuery改变了两个div的CSS属性(JQuery change CSS property of two div's)
  • JDK中包含的库版本(Versions of libraries included in the JDK)
  • 请问下载的是出现ASP是什么意思
  • Firebase MLkit用于数字液晶显示器的文本识别(Firebase MLkit Text recognition for digital lcd displays)
  • 我可以在任何平台上运行C和C ++吗?(Can I run C and C++ on any platform?)
  • 让小组在C#的特定位置(get panel at specific positions in C#)
  • Nagios为通知设置了更高的间隔(Nagios set higher interval for notifications)
  • 无法向SMTP主机发送电子邮件(unable to send an email to SMTP host)
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何在.NET代码中验证全球邮政编码(How can I validate worldwide postal codes in my .NET code)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • Clojure:减少大型懒惰收集会占用内存(Clojure: Reducing large lazy collection eats up memory)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • 显示作为字符串的SVG(Showing an SVG that I have as a string)
  • 从jansson库里创建json请求的自由内存的正确方式是什么?(what is the proper way of free memory in creating json request from jansson libary?)
  • jQuery插件无法正常工作 - 它是附加的(jQuery plugin not working - it's appended)
  • 使用stat_summary自动调整ylim(Automatically adjusting ylim with stat_summary)