如何解决通过 region->put 更新缓存时,无法将 afterCreate 事件转换为 PdxInstance
当通过 Geode 的 REST API 更新区域时,我能够将缓存侦听器的 afterCreate 事件值转换为 PdxInstance 数据类型。下面的代码运行良好,没有任何问题。但是,当我尝试使用 Geode 提供的 Order.hpp 和 Order.cpp 示例代码通过自定义定义的 pdx 序列化更新区域时,下面我定义的缓存侦听器中的动态转换返回了一个内存地址为 0x0 的值,因此当它尝试访问订单对象中的字段,它给了我分段错误。 objectsize() 方法也返回 0 字节,这表明 pdx 序列化没有正确完成。
有人能告诉我下面我做错了什么吗?
#include <iostream>
#include <sstream>
#include <string>
#include <geode/CacheFactory.hpp>
#include <geode/PoolManager.hpp>
#include <geode/RegionFactory.hpp>
#include <geode/RegionShortcut.hpp>
#include <geode/TypeRegistry.hpp>
#include <geode/AttributesMutator.hpp>
#include <geode/CacheListener.hpp>
#include <geode/EntryEvent.hpp>
#include <geode/CacheableString.hpp>
#include <geode/PdxInstance.hpp>
#include "Order.hpp"
using namespace apache::geode::client;
using namespace customserializable;
class MyEventHandler : public CacheListener
{
public:
void afterCreate(const EntryEvent& event) override
{
auto key(dynamic_cast<CacheableString *>(event.getKey().get()));
std::cout << "afterCreate: " << key->value() << std::endl;
auto mypdx = event.getNewValue().get();
mypdx->toString();
mypdx->objectsize();
PdxInstance *pdx = dynamic_cast<PdxInstance *>(mypdx);
// auto pdx(dynamic_cast<PdxInstance *>(mypdx));
int order_id = pdx->getByteField("order_id");
int quantity = pdx->getByteField("quantity");
std::string name = pdx->getStringField("name");
std::cout << "Testing" << std::endl;
}
};
auto MyListener = std::make_shared<MyEventHandler>();
int main(int argc,char** argv) {
auto cache = CacheFactory()
.set("log-level","none")
.setPdxReadSerialized(true)
.create();
cache.getPoolManager()
.createFactory()
.addLocator("localhost",10334)
.setSubscriptionEnabled(true)
.create("pool");
auto regionFactory = cache.createRegionFactory(RegionShortcut::CACHING_PROXY);
auto region = regionFactory.setPoolName("pool").create("custom_orders");
cache.getTypeRegistry().registerPdxType(Order::createDeserializable);
region->getAttributesMutator()->setCacheListener(MyListener);
std::cout << "Create orders" << std::endl;
auto order1 = std::make_shared<Order>(1,"product x",23);
auto order2 = std::make_shared<Order>(2,"product y",37);
region->registerallKeys();
region->put("Order19",order1);
cache.close();
}
解决方法
明确地说,我们认为您在这里需要的是 dynamic_cast<Order*>(mypdx);
。让我们知道结果如何!
Geode 客户端开发人员在这里
顺序源自PdxSerializable
,而不是PdxInstance
。如果您查看它们的继承层次结构,您会发现它们是彼此的兄弟姐妹,而不是另一个的后代。除其他外,动态转换也是一种运行时类型查询,因此您实际上是在询问 mypdx
是否从 PdxInstance
派生,并且返回 nullptr
是指示 {{ 1}},这是正确的。改变演员表的类型,我想你会得到更令人满意的结果。
祝你好运,继续提问,我们确实会努力关注和回应。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。