我是clojure的新手,我正在编写一个库,将发布结果发送到服务器以获得响应.我通过将响应放在core.async通道上来消耗响应.这是理智还是有更好的方法?
以下是我正在做的事情的高级概述:
(defn my-post-request [channel options]
(client/post http://www.example.com options
(fn [{:keys [status headers body error]}] ;; asynchronous handle response
(go (>! channel body)))))
(defn request-caller [options]
(let [channel (chan)]
(my-post-request channel options)
(json/parse-string (<!! (go (<! channel))))))
Run Code Online (Sandbox Code Playgroud)
以下是我使用的实际代码:https://github.com/gilmaso/btc-trading/blob/master/src/btc_trading/btc_china.clj#L63
它有效,但我很难确认这是否是正确的方法.
使用频道时,future建议还是thread?是否有时候future更有意义?
Rich Hickey关于core.async的博文建议使用thread而不是future:
虽然你可以在使用例如future创建的线程上使用这些操作,但是还有一个宏,线程,类似于go,它将启动一流的线程并类似地返回一个通道,并且应该优先考虑未来的通道工作.
~ http://clojure.com/blog/2013/06/28/clojure-core-async-channels.html
但是,core.async示例在使用future通道时会广泛使用:
(defn fake-search [kind]
(fn [c query]
(future
(<!! (timeout (rand-int 100)))
(>!! c [kind query]))))
Run Code Online (Sandbox Code Playgroud)
~ https://github.com/clojure/core.async/blob/master/examples/ex-async.clj
我从我的python实现获得的HMAC SHA1签名和我的clojure实现略有不同.我很难过会导致这种情况.
Python实现:
import hashlib
import hmac
print hmac.new("my-key", "my-data", hashlib.sha1).hexdigest() # 8bcd5631480093f0b00bd072ead42c032eb31059
Run Code Online (Sandbox Code Playgroud)
Clojure实施:
(ns my-project.hmac
(:import (javax.crypto Mac)
(javax.crypto.spec SecretKeySpec)))
(def algorithm "HmacSHA1")
(defn return-signing-key [key mac]
"Get an hmac key from the raw key bytes given some 'mac' algorithm.
Known 'mac' options: HmacSHA1"
(SecretKeySpec. (.getBytes key) (.getAlgorithm mac)))
(defn sign-to-bytes [key string]
"Returns the byte signature of a string with a given key, using a SHA1 HMAC."
(let [mac (Mac/getInstance algorithm)
secretKey (return-signing-key key mac)]
(-> (doto mac …Run Code Online (Sandbox Code Playgroud)