You don't even need to use a static field in your servlet, you can use a
normal class field, like this:
public class MyServlet extends HttpServlet {
private Cache cache;
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
CacheFactory cacheFactory =
CacheManager.getInstance().getCacheFactory();
this.cache = cacheFactory.createCache(Collections.EMPTY_MAP);
} catch (CacheException exc) {
logger.error("Could not create cache: " + exc.getMessage(),exc);
throw new ServletException(exc);
}
}
}
This works because a servlet is only instantiated once (at application
startup) and if there are multiple servers needed for your app, each Cache
will point to the same memcache service.
You need to store the list also elsewhere however, because the memcache
entry can be removed at any time, so you need to check if it is still in the
cache before using it:
List list = cache.get("mylist");
if (list == null) {
list = buildList();
cache.put('list",list);
}
On Sun, May 2, 2010 at 6:07 PM, lembas <[email protected]> wrote:
> I have the list of city names of my country in my database. It is so
> rare to add a new city. The list is the same for every user for every
> session. So I use cache for the list. I want to read the list from DB
> only for once and to keep it on cache as long as possible.
>
> Do I need the following everytime I need cache object?
>
> try {
> CacheFactory cacheFactory =
> CacheManager.getInstance().getCacheFactory();
> cache = cacheFactory.createCache(Collections.emptyMap());
> } catch (CacheException e) {
> // ...
> }
>
> Or is it ok to save it with
> getServletContext().setAttribute("cache", cache);
> and get it with when I need it?
> getServletContext().getAttribute("cache")
>
> or can I keep it on a static field of MyServlet class?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Google App Engine for Java" group.
> To post to this group, send email to
> [email protected].
> To unsubscribe from this group, send email to
> [email protected]<google-appengine-java%[email protected]>
> .
> For more options, visit this group at
> http://groups.google.com/group/google-appengine-java?hl=en.
>
>
--
Pieter Coucke
Onthoo BVBA
http://www.onthoo.com
http://www.koopjeszoeker.be
--
You received this message because you are subscribed to the Google Groups
"Google App Engine for Java" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/google-appengine-java?hl=en.