在 Clojure 中定义 SPI [英] Defining a SPI in Clojure

查看:10
本文介绍了在 Clojure 中定义 SPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种惯用的方法来在 Clojure 中定义可由外部服务提供者"实现的接口.我的应用程序将在运行时定位并实例化服务提供者模块,并将某些职责委派给它.

I'm looking for an idiomatic way(s) to define an interface in Clojure that can be implemented by an external "service provider". My application would locate and instantiate the service provider module at runtime and delegate certain responsibilities to it.

比方说,例如,我正在实现一个 RPC 机制,并且我希望允许在配置时注入自定义中间件.该中间件可以对消息进行预处理、丢弃消息、使用日志记录包装消息处理程序等.

Let's say, for example, that I'm implementing a RPC mechanism and I want to allow a custom middleware to be injected at configuration time. This middleware could pre-process the message, discard messages, wrap the message handler with logging, etc.

如果我回到 Java 反射,我知道有几种方法可以做到这一点,但我觉得在 Clojure 中实现它会有助于我的理解.

I know several ways to do this if I fall back to Java reflection, but feel that implementing it in Clojure would help my understanding.

(注意,我在这里使用的是一般意义上的 SPI,并不是特指 JAR 文件规范)

(Note, I'm using SPI in a general sense here, not specifically referring to the way it's defined in the JAR file specification)

谢谢

推荐答案

Clojure 是一种非常动态的语言:几乎可以在编译时完成的任何事情都可以在运行时完成.您的部署配置"可能只是一个在运行时加载到应用程序中的 clojure 源文件.只需调用(加载my-config.clj").请注意,如果您真的愿意,您甚至可以覆盖特定动态范围内的函数,因此您可以将任何函数(包括核心函数)与另一个表示记录其参数、返回值和多长时间的函数一起包装他们跑了.有关如何执行此操作的示例,请查看 clojure.contrib.trace.

Clojure is a very dynamic language: almost anything that can be done at compile time can be done at runtime. Your "deployment configuration" could simply be a clojure source file that gets loaded into the application at runtime. Just call (load "my-config.clj"). Note that you can even override functions in a particular dynamic scope if you really want to, so you can wrap any function (including core functions) with another one that say logs their arguments, return value and how long they took to run. Have a look at clojure.contrib.trace for an example of how to do this.

这篇关于在 Clojure 中定义 SPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆