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

查看:121
本文介绍了在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天全站免登陆