Cache2kPostgresServlet.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package hello;
  2. import java.io.*;
  3. import java.sql.*;
  4. import java.util.*;
  5. import java.util.concurrent.*;
  6. import javax.annotation.*;
  7. import javax.servlet.*;
  8. import javax.servlet.http.*;
  9. import javax.sql.*;
  10. import org.cache2k.Cache;
  11. import org.cache2k.Cache2kBuilder;
  12. /**
  13. * Cache
  14. */
  15. @SuppressWarnings("serial")
  16. public class Cache2kPostgresServlet extends HttpServlet {
  17. // Database details.
  18. private static final int DB_ROWS = 10000;
  19. private static final int LIMIT = DB_ROWS + 1;
  20. // Database connection pool.
  21. @Resource(name = "jdbc/hello_world")
  22. private DataSource dataSource;
  23. private Cache<Integer, CachedWorld> cache;
  24. @Override
  25. public void init(ServletConfig config) throws ServletException {
  26. super.init(config);
  27. Map<Integer, CachedWorld> worlds;
  28. try {
  29. worlds = Common.loadAll(dataSource.getConnection());
  30. } catch (SQLException e) {
  31. throw new ServletException(e);
  32. }
  33. // Build the cache
  34. cache = new Cache2kBuilder<Integer, CachedWorld>() {}
  35. .name("cachedWorld")
  36. .eternal(true)
  37. .entryCapacity(DB_ROWS)
  38. .build();
  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 Random random = ThreadLocalRandom.current();
  46. //TODO prevent duplicate numbers to be added
  47. List<Integer> keys = new ArrayList<Integer>(count);
  48. for (int i = 0; i < count; i++) {
  49. keys.add(new Integer(random.nextInt(LIMIT)));
  50. }
  51. // Set content type to JSON
  52. res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
  53. // Write JSON encoded message to the response.
  54. Common.MAPPER.writeValue(res.getOutputStream(), cache.getAll(keys).values());
  55. }
  56. }