Cache2kPostgresServlet.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package hello;
  2. import java.io.IOException;
  3. import java.sql.SQLException;
  4. import java.util.Map;
  5. import java.util.concurrent.ThreadLocalRandom;
  6. import javax.annotation.Resource;
  7. import javax.servlet.ServletConfig;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import javax.sql.DataSource;
  13. import org.cache2k.Cache;
  14. import org.cache2k.Cache2kBuilder;
  15. import org.cache2k.IntCache;
  16. /**
  17. * Cache
  18. */
  19. @SuppressWarnings("serial")
  20. public class Cache2kPostgresServlet extends HttpServlet {
  21. // Database details.
  22. private static final int DB_ROWS = 10000;
  23. // Database connection pool.
  24. @Resource(name = "jdbc/hello_world")
  25. private DataSource dataSource;
  26. private IntCache<CachedWorld> cache;
  27. @Override
  28. public void init(ServletConfig config) throws ServletException {
  29. super.init(config);
  30. Map<Integer, CachedWorld> worlds;
  31. try {
  32. worlds = Common.loadAll(dataSource.getConnection());
  33. } catch (SQLException e) {
  34. throw new ServletException(e);
  35. }
  36. // Build the cache
  37. cache = new Cache2kBuilder<Integer, CachedWorld>() {
  38. }.name("cachedWorld").eternal(true).entryCapacity(DB_ROWS).buildForIntKey();
  39. cache.putAll(worlds);
  40. }
  41. @Override
  42. protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
  43. IOException {
  44. final int count = Common.normalise(req.getParameter("queries"));
  45. final CachedWorld[] worlds = new CachedWorld[count];
  46. for (int i = 0; i < count; i++) {
  47. worlds[i] = cache.peek(ThreadLocalRandom.current().nextInt(DB_ROWS) + 1);
  48. }
  49. // Set content type to JSON
  50. res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
  51. // Write JSON encoded message to the response.
  52. Common.MAPPER.writeValue(res.getOutputStream(), worlds);
  53. }
  54. }