Cache2kPostgresServlet.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. /**
  16. * Cache
  17. */
  18. @SuppressWarnings("serial")
  19. public class Cache2kPostgresServlet extends HttpServlet {
  20. // Database details.
  21. private static final int DB_ROWS = 10000;
  22. // Database connection pool.
  23. @Resource(name = "jdbc/hello_world")
  24. private DataSource dataSource;
  25. private Cache<Integer, CachedWorld> cache;
  26. @Override
  27. public void init(ServletConfig config) throws ServletException {
  28. super.init(config);
  29. Map<Integer, CachedWorld> worlds;
  30. try {
  31. worlds = Common.loadAll(dataSource.getConnection());
  32. } catch (SQLException e) {
  33. throw new ServletException(e);
  34. }
  35. // Build the cache
  36. cache = new Cache2kBuilder<Integer, CachedWorld>() {
  37. }.name("cachedWorld").eternal(true).entryCapacity(DB_ROWS).build();
  38. cache.putAll(worlds);
  39. }
  40. @Override
  41. protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
  42. IOException {
  43. final int count = Common.normalise(req.getParameter("queries"));
  44. final CachedWorld[] worlds = new CachedWorld[count];
  45. for (int i = 0; i < count; i++) {
  46. worlds[i] = cache.get(ThreadLocalRandom.current().nextInt(DB_ROWS) + 1);
  47. }
  48. // Set content type to JSON
  49. res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
  50. // Write JSON encoded message to the response.
  51. Common.MAPPER.writeValue(res.getOutputStream(), worlds);
  52. }
  53. }