Home >Database >Redis >How to serialize redisson

How to serialize redisson

(*-*)浩
(*-*)浩Original
2019-11-27 10:00:455925browse

How to serialize redisson

Redisson is a Java memory-resident data grid implemented on the basis of Redis. Compared with Jedis, which exposes underlying operations, Redisson provides a series of distributed Java common objects and also provides many distributed services. (Recommended learning: Redis video tutorial)

Serialization

Redisson’s object encoding class is used to convert objects Perform serialization and deserialization to read and store the object in Redis.

The default encoder by Redisson is JsonJacksonCodec. When JsonJackson serializes objects with bidirectional references, an infinite loop exception will occur. After fastjson checks out the double reference, it will automatically replace it with the reference character $ref and terminate the cycle.

In my case, I serialized a service. This service has been hosted by spring, and it is also injected into another service. Fastjson can be used to serialize to redis normally, while JsonJackson can Throws infinite loop exception.

In order to make the serialized content visible, there is no need to use redission’s other built-in binary encoders and implement the encoder by yourself:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import org.redisson.client.codec.BaseCodec;
import org.redisson.client.protocol.Decoder;
import org.redisson.client.protocol.Encoder;

import java.io.IOException;

public class FastjsonCodec extends BaseCodec {

 private final Encoder encoder = in -> {
 ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
 try {
 ByteBufOutputStream os = new ByteBufOutputStream(out);
 JSON.writeJSONString(os, in,SerializerFeature.WriteClassName);
 return os.buffer();
 } catch (IOException e) {
 out.release();
 throw e;
 } catch (Exception e) {
 out.release();
 throw new IOException(e);
 }
 };

 private final Decoder<Object> decoder = (buf, state) ->
 JSON.parseObject(new ByteBufInputStream(buf), Object.class);

 @Override
 public Decoder<Object> getValueDecoder() {
 return decoder;
 }

 @Override
 public Encoder getValueEncoder() {
 return encoder;
 }
}

More Redis related technical articles, Please visit the Redis Getting Started Tutorial column to learn!

The above is the detailed content of How to serialize redisson. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn