jReflectServer - distributed code example

In this example you can see how to implement a distributed session-based requested page counter. First, we create the Counter class. Instances of this class represent the count of requests per session. They will be stored in the distributed session. Therefore the object must implement Serializable.

class Counter implements Serializable {

   private int c = 0;

 

   public void increment() {

       c++;

   }

 

   public void decrement() {

       c--;

   }

 

   public int value() {

       return c;

   }

 

   @Override

   public String toString() {

       return Integer.toString(c);

   }

}

 

Now the actual implementation of the webpage:

public class CounterPage implements WebPage {

 

   @Override

   @WebPage.Route("CounterPage")

   public void generatePage(JReflectServer server, WebRequest request, WebResponse response) throws Exception {

       Session currentSession = request.getSession();

       Counter counter = current.getAttribute("counter");

       if (counter == null) {

           counter = new Counter();

           currentSession.setAttribute("counter", counter);

       }

       counter.increment();

       response.text(200, "Counted " + counter.value() + " on node " + server.getId());            

   }

 

}

 

When you launch CounterPage on multiple server instances (see in the main tutorial) you will see the couter increament by 1 with each request. However, the server IDs will be different since the code will be executed on different nodes.

For the session to work, cookies must be enabled in order to allow jRequestServer store the session ID in a cookie.