How to maintain state in different user sessions in a ring application

I need to maintain global state on the server in different browser / user sessions.

My assumption is that all atoms, etc., created when entering a query are specific to that query. As soon as the answer returns, all this state is destroyed, and memory is freed. Please correct me if I am wrong.

The state of requests for a particular session can be maintained in memory using session middleware.

However, how do I maintain state through multiple user sessions and queries. If possible, I would like to avoid using memcached / redis, etc. For storage from the outside. Is it possible to achieve this in memory itself?

+5
source share
1 answer

You want to say that you want the global state to be common to all sessions?

If it's that simple, just declare an atom or ref in any namespace you like and it will be available for all sessions, for example:

(def my-state (atom {:foo 1 :bar 2}))

This works because the Clojure environment persists as long as the application server continues to work, and any future requests will be able to observe / change the global state.

Having said all this, it is worth remembering that global status is often the smell of design . You should think about whether you really need it, or if you should consider another alternative (for example, pushing the general state into the database).

+8
source

All Articles