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
最满意答案
坦率地说,你的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 aselect_related('category')
you should add this as well since your fetching the category for all book objects inget_category_url
.
相关问答
更多-
将查询集的内容添加到Django / Python中的列表中(Adding contents of a queryset to a list in Django/Python)[2023-01-15]
至于为什么你的代码会引发一个错误:你必须使用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 ... -
仅限Django Queryset(Django Queryset only)[2022-08-12]
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' 为了分割结果,使用偏 ...
-
django queryset api - 使用带有字段列表的values方法(django queryset api - using values method with a list of fields)[2023-05-02]
你需要解压缩值:) 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记录,包括迭代 ...