I'd like to save database results in memory because my database only changes between long time intervals. By building a minimum application, I see my cache-strategy seems to work per servlet: by opening a new browser, the first request yields a cache-miss.
Looking through the documentation, I got the idea that perhaps I should serve/servlet using
#:servlet-namespace '("shared-model.rkt")
where shared-model.rkt is the module that talks to the database and implements the caching-strategy. But adding this keyword to serve/servlet did not make any perceived difference.
What should I do to save results in memory across all requests?
--- server.rkt
--------------------------------------------------------------------------
#lang racket/base
(require
web-server/servlet
web-server/servlet-env
(prefix-in model: "shared-model.rkt"))
(define-values (dispatch url)
(dispatch-rules
(("main") db->response)
(("update" (string-arg)) update->response)))
(define (update->response r s)
(define str (model:in-memory-db-set-and-get s))
(displayln str)
(string->response str))
(define (db->response r)
(string->response (model:get-in-memory-results)))
;; no more api endpoints ==/==
(define (string->response s)
(response/full 200 #"Okay" (current-seconds)
TEXT/HTML-MIME-TYPE '() (list (string->bytes/utf-8 s))))
(define (file-not-found r)
(response/xexpr "File not found."))
(module+ main
(file-stream-buffer-mode (current-output-port) 'line)
(define (main)
(displayln "Now serving...")
(serve/servlet dispatch
;; #:servlet-namespace '("shared-model.rkt")
#:stateless? #t
#:log-file (build-path "logs/httpd.log")
#:port 1111
#:listen-ip "127.0.0.1"
#:servlet-path "/"
#:servlet-regexp #rx""
#:extra-files-paths (list (build-path "pub/"))
#:server-root-path (build-path "/")
#:file-not-found-responder file-not-found))
(main))
---------------------------------------------------------------------------
--- shared-model.rkt
---------------------------------------------------------------------------
#lang racket/base
(define in-memory-database (make-parameter #f))
(define (in-memory-db-set-and-get x)
(in-memory-database (format "~a: data to be shared across servlets" x))
(in-memory-database))
(define (get-in-memory-results [refresh? #f])
(if refresh?
(begin (displayln "database: force refresh")
(in-memory-db-set-and-get "forced"))
(let ([in-memory-db (in-memory-database)])
(if in-memory-db
(begin (displayln "database: cache hit")
in-memory-db)
(begin (displayln "database: cache miss")
(in-memory-db-set-and-get "miss"))))))
(provide (all-defined-out))
---------------------------------------------------------------------------