How can I store Objects in cassandra using the blob datatype

荒凉一梦 提交于 2019-12-06 11:13:09

From documentation

blob  | blobs  |  Arbitrary bytes (no validation), expressed as hexadecimal

so what you need is provided by the Bytes class. The following is an interface I use to serialize/deserialize Java objects I need to save in Cassandra

public interface Bufferable extends Serializable {

    static final Logger LOGGER = LoggerFactory.getLogger(Bufferable.class);

    default ByteBuffer serialize() {
        try (ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bytes);) {
            oos.writeObject(this);
            String hexString = Bytes.toHexString(bytes.toByteArray());
            return Bytes.fromHexString(hexString);
        } catch (IOException e) {
            LOGGER.error("Serializing bufferable object error", e);
            return null;
        }
    }

    public static Bufferable deserialize(ByteBuffer bytes) {
        String hx = Bytes.toHexString(bytes);
        ByteBuffer ex = Bytes.fromHexString(hx);
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(ex.array()));) {
            return (Bufferable) ois.readObject();
        } catch (ClassNotFoundException | IOException e) {
            LOGGER.error("Deserializing bufferable object error", e);
            return null;
        }
    }
}

HTH, Carlo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!