What I want to accomplish is a sane way of storing a list of the pages visited during each anonymous user session on my website. It is important that the sequence is correct and that one users navigation is not mixed up with another ones.
It is similar to this C# question: "track visitor info on every request", where they proposed to use a logfile for short-term storage. My site will only host ~2K users/day so I think I would be fine with having the cache in memory (atleast that seems easier).
I cant seem to figure out a solution that will work with the stateless Play framework since the solution requires saving data(to DB) only when an user has timed out and is not active anymore. My idea would rely on storing each request in memory and then call the database if a new request hasnt arrived in a certain time (user timeout). How would it be possible to do that?
Is there any other way you think might be better, perhaps storing all the requests from all users and then making a big write to db instead of one for each session?
EDIT:
I have now taken the easy way out, it would have been great to do what Salem mentioned but I cant figure out how to save a list to memory. My first plan was actually to use the Akka scheduler that would be altered (timer reset and a new post added) each time the user gets a new page but I simply dont know how to get in touch with a instance ion memory from a previous request so if someone could tell me that I would be very grateful.
For now I have solved my problem the "bad way" with requests to database for each page view. Code below in case someone also wanna be bad:
In the Action:
String uuid=session("uuid");
Logger.info("Old uuid:"+uuid);
String generatedId = UserTracker.updateTracker(uuid,id.toString()).toString();
if(uuid==null || !generatedId.equals(uuid)){
Logger.info("new UUID for user:"+generatedId);
session("uuid", generatedId);
}
UserTracker class:
@Entity
public class UserTracker extends Model {
@Id
@SequenceGenerator(name="ut_gen", sequenceName="user_tracker_seq", allocationSize=1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="ut_gen")
long session_id;
String navigations;
public static Long updateTracker(String session,String page){
UserTracker ut=null;
try{
Long sessionId=Long.parseLong(session);
ut = UserTracker.find.byId(sessionId);
if(ut!=null)
{
ut.addPage(page);
ut.update();
} else {
throw new NumberFormatException();
}
} catch (NumberFormatException e){
ut = new UserTracker(page);
ut.save();
}
return ut.session_id;
}
private void addPage(String page) {
// TODO Auto-generated method stub
if(navigations!=null && !navigations.isEmpty())
navigations+=","+page;
else
navigations=page;
}
public UserTracker(String page){
addPage(page);
save();
}
public static Finder<Long,UserTracker> find =
new Finder<Long,UserTracker>(Long.class,UserTracker.class);
}