Over a million developers have joined DZone.

A Look at the Java Distributed In-Memory Data Model (Powered by Redis)

This article details Redisson's LiveObject concept, which can help model data for distributed applications.

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

There are a lot of frameworks (Coherence, Terracota, Redisson, GridGain, Hazelcast, Infinispan, etc.) nowadays that offer Java the ability to access distributed in-memory utility data types such as Map, Cache, etc.

In reality, we are often required to work directly with business data models of an application. The complexity is usually way beyond those utility data types' ability to comprehend. That's why, despite having all these distributed in-memory utility data types at hand, people are stilling using JPA to persist their business data.

While changes in the distributed in-memory data model should be reflected in real-time, it should be able to achieve that without the need to serialize and deserialize the whole object.

The LiveObject concept offered by Redisson has solved this stiff challenge. A detailed description of it was made in a previous article. Now, let's take a look at a practical application.

Here is a typical business data model diagram:

Image title

Below is the Java implementation of that data model.

Customer object:

@REntity
public static class Customer {
    @RId(generator = UUIDGenerator.class)
    private String id;
    private List<Order> orders;
    private String name;
    private String address;
    private String phone;
    protected Customer() {
    }

    public Customer(String id) {
        super();
        this.id = id;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getAddress() {
        return address;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPhone() {
        return phone;
    }

    public void addOrder(Order order) {
        orders.add(order);
    }

    public List<Order> getOrders() {
        return orders;
    }

    public String getId() {
        return id;
    }
}


Order object:

@REntity
public static class Order {

    @RId(generator = LongGenerator.class)
    private Long id;

    private List<OrderDetail> orderDetails; 

    private Customer customer;

    private Date date;

    private Date shippedDate;

    private String shipName;
    private String shipAddress;
    private String shipPostalCode;

    protected Order() {
    }

    public Order(Customer customer) {
        super();
        this.customer = customer;
    }

    public List<OrderDetail> getOrderDetails() {
        return orderDetails;
    }

    public Customer getCustomer() {
        return customer;
    }

    public Long getId() {
        return id;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Date getShippedDate() {
        return shippedDate;
    }

    public void setShippedDate(Date shippedDate) {
        this.shippedDate = shippedDate;
    }

    public String getShipName() {
        return shipName;
    }

    public void setShipName(String shipName) {
        this.shipName = shipName;
    }

    public String getShipAddress() {
        return shipAddress;
    }

    public void setShipAddress(String shipAddress) {
        this.shipAddress = shipAddress;
    }

    public String getShipPostalCode() {
        return shipPostalCode;
    }

    public void setShipPostalCode(String shipPostalCode) {
        this.shipPostalCode = shipPostalCode;
    }

}


OrderDetail object:

@REntity
public static class OrderDetail {

    @RId(generator = LongGenerator.class)
    private Long id;

    private Order order;

    private Product product;

    private BigDecimal price;
    private Integer quantity;
    private BigDecimal discount;

    protected OrderDetail() {
    }

    public OrderDetail(Order order, Product product) {
        super();
        this.order = order;
        this.product = product;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    public BigDecimal getDiscount() {
        return discount;
    }

    public void setDiscount(BigDecimal discount) {
        this.discount = discount;
    }

    public Long getId() {
        return id;
    }

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }

    public Product getProduct() {
        return product;
    }

}


Product object:

@REntity
public static class Product {

    @RId
    private Long id;
    private String name;

    private Map<String, Integer> itemName2Amount;

    private BigDecimal price;
    private Integer unitsInStock;

    protected Product() {
    }

    public Product(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setUnitsInStock(Integer unitsInStock) {
        this.unitsInStock = unitsInStock;
    }

   public Integer getUnitsInStock() {
        return unitsInStock;
    }

    public String getName() {
        return name;
    }

    public void addItem(String name, Integer amount) {
        getItemName2Amount().put(name, amount);
    }

    public Integer getItemAmount(String name) {
        return getItemName2Amount().get(name);
    }

    Map<String, Integer> getItemName2Amount() {
        return itemName2Amount;
    }
}

Please notice that we encapsulated itemName2Amount field made its getter visibility as protected. 

Here is an example of work with data model described above:

        RLiveObjectService liveObjectService = redisson.getLiveObjectService()

        Customer customer = new Customer("12");
        // customer object is becoming "live" object
        customer = liveObjectService.merge(customer);

        customer.setName("Alexander Pushkin");
        customer.setPhone("+7193127489123");
        customer.setAddress("Moscow, Tverskaya str");

        Product product = new Product(1L, "FoodBox");
        // product object is becoming "live" object
        product = liveObjectService.merge(product);

        product.addItem("apple", 1);
        product.addItem("banana", 12);
        product.setPrice(BigDecimal.valueOf(10));
        product.setUnitsInStock(12);

        Order order = new Order(customer);
        // order object is becoming "live" object
        order = liveObjectService.merge(order);

        order.setDate(new Date());
        order.setShipAddress("Moscow, Gasheka str");
        order.setShipName("James Bond");
        order.setShipPostalCode("141920");

        OrderDetail od = new OrderDetail(order, product);
        // OrderDetail object is becoming "live" object
        od = liveObjectService.merge(od);

        od.setPrice(BigDecimal.valueOf(9));
        od.setQuantity(1);

        order.getOrderDetails().add(od);
        customer.getOrders().add(order);

        // "live" object could be get on other JVM.
        Customer customer = liveObjectService.get(Customer.class, "12");
        for (Order order : customer.getOrders()) {
            for (OrderDetail orderDetail : order.getOrderDetails()) {
                 // ...
            }
            order.setPrice(BigDecimal.valueOf(12))
        }

        Product product = liveObjectService.get(Product.class, id);
        // ...

The merge, get, persist, attach methods of the RLiveObjectService object return a proxy-object which connected to Redis and that's what make it a liveobject. This proxy translates each getter/setter call to read/write Redis operation in real time.

As seen from the example above, each object has an id field marked by the RId annotation. The id value can come from two difference places: provided by users or generated by a generator (LongGenerator.class, UUIDGenerator.class or any other implementation) LongGenerator returns incremented value which is unique for each type of Object.

The RCascade annotation allows you to cascade RLiveObjectService operations (merge, persist, delete) for marked fields.

The pseudo code below illustrates the store of the described data model in Redis used by Redisson:

redis.hset "customer:12" "name" "Alexander Pushkin"  
redis.hset "customer:12" "phone" "+7193127489123"  
redis.hset "customer:12" "address" "Moscow, Tverskaya 1 str"  

redis.incr "product:long:generator"  

redis.hset "product:1:long" "name" "FoodBox"  
redis.hset "product:1:long" "price" 10  
redis.hset "product:1:long" "unitsInStock" 12  
redis.hset "product:1:long" "items" "org.javamodel.Product:product:1:long:items"  

redis.hset "product:1:long:items" "apple" 1  
redis.hset "product:1:long:items" "banana" 12  

redis.incr "order:long:generator"  

redis.hset "order:1:long" "customer" "org.javamodel.Customer:customer:12"  
redis.hset "order:1:long" "orderDetails" "org.redisson.RedissonList:orderDetails:order:1:long"  
redis.hset "order:1:long" "date" "144516271223"  
redis.hset "order:1:long" "shipAddress" "Moscow, Gasheka 9 str"  
redis.hset "order:1:long" "shipName" "James Bond"  
redis.hset "order:1:long" "shipPostalCode" "141920"  

redis.incr "orderdetail:long:generator"

redis.hset "orderdetail:1:long" "order" "org.javamodel.Order:order:1"  
redis.hset "orderdetail:1:long" "product" "org.javamodel.Product:product:1:long"  
redis.hset "orderdetail:1:long" "price" 9  
redis.hset "orderdetail:1:long" "quantity" 1  

redis.rpush "org.redisson.RedissonList:orderDetails:order:1:long" "orderdetail:1:long"  

redis.incr "orderdetail:long:generator"  

redis.hset "orderdetail:2:long" "order" "org.javamodel.Order:order:1"  
redis.hset "orderdetail:2:long" "product" "org.javamodel.Product:product:2:long"  
redis.hset "orderdetail:2:long" "price" 4  
redis.hset "orderdetail:2:long" "quantity" 2  

redis.rpush "org.redisson.RedissonList:orderDetails:order:1:long" "orderdetail:2:long"  

As you can see, all properties of objects are mapped directly to the Redis hash object. References to objects are stored as strings, which contains the type and id of this object. List and Map objects are mapped directly to Redis hash/list objects, too.

Conclusions

This approach greatly simplifies the work for creating a distributed business application with the help of Redisson's distributed in-memory Java data model. It also reduces the time of the round-trip for read/write data. It's worth noting that LiveObject conception allows us to interact with a Java data model of any complexity and even with a huge amount of fields.

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:
redis ,distributed applications ,java ,data model

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}