3 Ways to Use Redis Hash in Java
Check out this comparison of Jedis, Spring Data Redis, and Redisson to see how each library talks to Redis and interacts with hashes.
Join the DZone community and get the full member experience.
Join For FreeNeedless to say, Map is vital and the most popular structure in Java. Redis has offered a data structure that closely resembles Java's Map structure, which has attracted a lot of interest from Java developers. There has been a growing number of Java libraries that talk to Redis, most of which have provided a way to interact with Redis Hashes. Let's compare three different ways of interacting with Redis Hash in Java through examples of using three most popular Redis Java clients - Jedis, Spring Data Redis and Redisson. In order to make them easy to understand and fairly comparable, each example uses the same popular binary codec, Kryo, to provide serialization/deserialization of the dummy data.
1. Jedis
Jedis only works with raw binary data so encoding/decoding logic are required each time when a Redis command is invoked. A Jedis instance also needs to be acquired each time from the instance pool before any command can be invoked.
private static byte[] encode(Kryo kryo, Object obj) {
ByteArrayOutputStream objStream = new ByteArrayOutputStream();
Output objOutput = new Output(objStream);
kryo.writeClassAndObject(objOutput, obj);
objOutput.close();
return objStream.toByteArray();
}
private static <T> T decode(Kryo kryo, byte[] bytes) {
return (T) kryo.readClassAndObject(new Input(bytes));
}
public static void main(String[] args) {
JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
Kryo kryo = new Kryo();
kryo.register(MyKey.class);
kryo.register(MyValue.class);
Jedis jedis = jedisPool.getResource();
MyKey key = new MyKey("Jhon", "+138129129113");
byte[] keyArray = encode(kryo, key);
MyValue value = new MyValue("Kremlin street", "Moscow");
byte[] valueArray = encode(kryo, value);
byte[] name = "myMap".getBytes();
// put
jedis.hset(name, keyArray, valueArray);
// get
byte[] mappedValueArray = jedis.hget(name, keyArray);
MyValue mappedValue = decode(kryo, mappedValueArray);
MyValue newValue = new MyValue("Kremlin street", "Moscow");
byte[] newValueArray = encode(kryo, newValue);
// putIfAbsent
jedis.hsetnx(name, keyArray, newValueArray);
jedis.close();
jedisPool.close();
}
2. Spring Data Redis
Spring Data Redis allows you to implement your own data serializer through the RedisSerializer
interface and use Jedis pools under the hood. So KryoSerializer needs to be implemented to in order to use the Kryo codec.
KryoSerializer Implementation
public static class KryoSerializer<T> implements RedisSerializer<T> {
private Kryo kryo;
public KryoSerializer(List<Class<?>> classes) {
kryo = new Kryo();
for (Class<?> clazz : classes) {
kryo.register(clazz);
}
}
@Override
public byte[] serialize(T t) throws SerializationException {
ByteArrayOutputStream objStream = new ByteArrayOutputStream();
Output objOutput = new Output(objStream);
kryo.writeClassAndObject(objOutput, t);
objOutput.close();
return objStream.toByteArray();
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
return (T) kryo.readClassAndObject(new Input(bytes));
}
}
Configuration
@Configuration
@ComponentScan
public static class Application {
@Bean
JedisConnectionFactory connectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setUsePool(true);
return factory;
}
@Bean
RedisTemplate<?, ?> redisTemplate(JedisConnectionFactory factory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setDefaultSerializer(new KryoSerializer<>(Arrays.asList(MyKey.class, MyValue.class)));
template.setConnectionFactory(factory);
return template;
}
}
Usage Example
@Component
public static class MapBean {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void execute() {
Kryo kryo = new Kryo();
kryo.register(MyKey.class);
kryo.register(MyValue.class);
MyKey key = new MyKey("Jhon", "+138129129113");
MyValue value = new MyValue("Pushkina street", "Moscow");
HashOperations<String, MyKey, MyValue> hashOperations = redisTemplate.opsForHash();
hashOperations.put("myKey", key, value);
MyValue mappedValue = hashOperations.get("myKey", key);
MyValue newValue = new MyValue("Tverskaya street", "Moscow");
hashOperations.putIfAbsent("myKey", key, newValue);
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
context.getBean(MapBean.class).execute();
context.close();
}
3. Redisson
Redisson supports many popular codecs, including Kryo. It maintains the connection pool and topology update for clusters, master/slave, and single Redis servers. The Redisson API covers not only Redis hash operations but also fully implements java.util.Map
and java.util.concurrent.ConcurrentMap
interfaces. It also supports map entry eviction and local cache for map entires.
public static void main(String[] args) {
Config config = new Config();
config.setCodec(new KryoCodec(Arrays.asList(MyKey.class, MyValue.class)))
.useSingleServer().setAddress("127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
RMap<MyKey, MyValue> map = redisson.getMap("myMap");
MyKey key = new MyKey("Jhon", "+138129129113");
MyValue value = new MyValue("Broad street", "New York");
map.put(key, value);
MyValue mappedValue = map.get(key);
MyValue newValue = new MyValue("Narrow street", "New York");
map.fastPutIfAbsent(key, newValue);
redisson.shutdown();
}
Conclusion
It is bluntly obvious that in terms of code simplicity, Redisson is a much better choice than other Redis Java clients when working with Redis Hashes. Or any other Redis structures for the same purpose, as a matter of fact, but that's for another post.
Opinions expressed by DZone contributors are their own.
Comments