Clojure: how to serialize a function and reuse it later

(defn my-func [opts]
  (assoc opts :something :else))

      

What I want to do is serialize a function reference (possibly via #'my-func

?) To a string such that I can deserialize it, call it using args.

How it works?

Edit - why is it not a duplicate

another question asked how to serialize a function body - all the function code. I am not asking how to do this. I am asking how to serialize a link.

Imagine a server cluster running the same bank attached to MQ. MQ pairs in fn-reference

and out fn-args

for functions in the bank, and the server in the cluster starts it up and starts it. This is what I am trying to do - don't skip function bodies.

In a way, this is similar to building a "serverless" engine in clojure.

+3


source to share


2 answers


Oddly enough, a commit to serialize the var id was added yesterday to Clojure: https://github.com/clojure/clojure/commit/a26dfc1390c53ca10dba750b8d5e6b93e846c067

So, from the latest snapshot of the wizard, you can serialize Var (for example #'clojure.core/conj

) and deserialize it to another JVM with access to the same loaded code and call it.



(import [java.io File FileOutputStream FileInputStream ObjectOutputStream ObjectInputStream])

(defn write-obj [o f]
  (let [oos (ObjectOutputStream. (FileOutputStream. (File. f)))]
    (.writeObject oos o)
    (.close oos)))

(defn read-obj [f]
  (let [ois (ObjectInputStream. (FileInputStream. (File. f)))
        o (.readObject ois)]
    (.close ois)
    o))

;; in one JVM
(write-obj #'clojure.core/conj "var.ser")

;; in another JVM
(read-obj "var.ser")

      

+5


source


As pointed out in the comments, if you can just serialize the keyword tag for this function and save / get that, you're done.

If you need to pass a function from one place to another, you need to send the source code of the function as a string and then compile it with eval

the other end. This is what Datomic does when the database function is stored in the DB and Datomic automatically starts on any new additions / changes to the DB (for example, they can do automatic data validation). Cm.:



How a similar technique is used in the book Clojure in Action (1st Edition) for an example with a distributed computing engine using RabbitMQ.

+5


source







All Articles