ankurjhawar
ankurjhawar

Reputation: 315

Setting a value to servicecontext in liferay

As per my code requirement, I need to get some user related information which is calculated based on a few DB calls to Organization and user group models. As per my performance review, there is a lot of time elapsed on the process, as this is done in multiple places.

As per a quick win, I prefer to do this only once at the time of login, but then I wish to store this information so that if can be used throughout the portal (in the hook, in a custom portlet, in themes, etc..).

In order to achieve this, I plan to use the following code, just wished to check whether there is any better solution (I used session in a non-Liferay based application, but always land in some phishing issue with Liferay):

ServiceContext sc = ServiceContextThreadLocal.getServiceContext();
sc.setAttribute("some-user-data", someUserData);

--

and in some portlet/hook, I do:

ServiceContext sc = ServiceContextThreadLocal.getServiceContext();
String someUserData = (String)sc.getAttribute("some-user-data");

Thanks! AJ

Upvotes: 0

Views: 937

Answers (1)

Olaf Kock
Olaf Kock

Reputation: 48067

AFAIK ServiceContext is not meant to survive a single request. The ThreadLocal will be thrown away or reinitialized for the next request that's handled, because most likely the next request handled by this request processor is handled for a completely different user.

You might want to look at cache dimensions, so that Organizations and User data is fetched from cache rather than from database. I'm assuming you're using Liferay's API for retrieving these.

Edit after your comment: I consider adding stuff to the session a very last resort, after all other options have been exhausted. Check the cache usage first, validate that indeed a lot of time is wasted through these calls, not just that the first one takes a while and the subsequent operations are called a lot of times. And don't validate this on a request-by-request-basis, but on actual use of your system: If you're optimizing a request that's only executed in 1% of cases in your system, and improve its performance by 5%, you won nothing. Instead you're ending up with a system that's harder to maintain, scale through a cluster, and that behaves weird if the database updates after you have saved your data in the session.

Upvotes: 1

Related Questions