Domanda

Suppongo che questa sia una strana domanda per la stragrande maggioranza dei programmatori che lavorano quotidianamente con Java. Io non. Conosco Java-the-language, perché ho lavorato su progetti Java, ma non Java-the-world. Non ho mai creato un'app Web da zero in Java. Se devo farlo con Python, Ruby, so dove andare (Django o Rails), ma se voglio creare un'applicazione Web in Clojure, non perché sono costretto a vivere in un mondo Java, ma perché come il linguaggio e voglio provarlo, quali librerie e framework dovrei usare?

È stato utile?

Soluzione

Di gran lunga il miglior framework Web Clojure che abbia mai incontrato è Compojure: http: // github. com / weavejester / compojure / albero / master

È piccolo ma potente e ha una sintassi meravigliosamente elegante. (Usa Jetty sotto il cofano, ma ti nasconde l'API Servlet a meno che tu non lo desideri, che non sarà spesso). Guarda il file README dell'URL, quindi scarica un'istantanea e inizia a giocare.

Altri suggerimenti

Compojure non è più un framework completo per lo sviluppo di applicazioni web. Dalla versione 0.4, il compojure è stato suddiviso in diversi progetti.

Ring fornisce le basi estraendo il processo di richiesta e risposta HTTP. Ring analizzerà la richiesta in arrivo e genererà una mappa contenente tutte le parti della richiesta come uri, nome server e metodo richiesta. L'applicazione gestirà quindi la richiesta e in base alla richiesta genererà una risposta. Una risposta è rappresentata come una mappa contenente i seguenti tasti: stato, intestazioni e corpo. Quindi una semplice applicazione sarebbe simile a:

(def app [req]
  (if (= "/home" (:uri req))
    {:status 200
     :body "<h3>Welcome Home</h3>"}
    {:status 200 
     :body "<a href='/home'>Go Home!</a>"}))

Un'altra parte di Ring è il concetto di middleware. Questo è il codice che si trova tra il gestore e la richiesta in arrivo e / o la risposta in uscita. Alcuni middleware integrati includono sessioni e stacktrace. Il middleware di sessione aggiungerà una: chiave di sessione alla mappa di richiesta che contiene tutte le informazioni sulla sessione per l'utente che effettua la richiesta. Se la chiave di sessione è presente nella mappa di risposta, verrà memorizzata per la richiesta successiva effettuata dall'utente corrente. Mentre il middleware di traccia dello stack acquisirà eventuali eccezioni che si verificano durante l'elaborazione della richiesta e genererà una traccia di stack che viene restituita come risposta se si verificano eccezioni.

Lavorare direttamente con Ring può essere noioso, quindi Compojure è costruito sopra l'anello che toglie il dettagli. L'applicazione ora può essere espressa in termini di routing in modo da poter avere qualcosa del genere:

(defroutes my-routes
  (GET "/" [] "<h1>Hello all!</h1>")
  (GET "/user/:id" [id] (str "<h1>Hello " id "</h1>")))

Compojure sta ancora lavorando con le mappe di richiesta / risposta, quindi puoi sempre accedervi se necessario:

(defroutes my-routes
  (GET "*" {uri :uri} 
           {:staus 200 :body (str "The uri of the current page is: " uri)}))

In questo caso la parte {uri: uri} accede alla chiave: uri nella mappa della richiesta e imposta uri su quel valore.

L'ultimo componente è Hiccup che semplifica la generazione dell'html. I vari tag html sono rappresentati come vettori con il primo elemento che rappresenta il nome del tag e il resto è il corpo del tag. "<h2>A header</h2>" diventa [:h2 "A Header"]. Gli attributi di un tag sono in una mappa opzionale. "<a href='/login'>Log In Page</a>" diventa [:a {:href "/login"} "Log In Page"]. Ecco un piccolo esempio che utilizza un modello per generare l'html.

(defn layout [title & body]
  (html
    [:head [:title title]]
    [:body [:h1.header title] body])) 

(defn say-hello [name]
  (layout "Welcome Page" [:h3 (str "Hello " name)]))

(defn hiccup-routes
  (GET "/user/:name" [name] (say-hello name)))

Ecco un link a una bozza di alcuni documenti attualmente in fase di scrittura dall'autore di compojure che potresti trovare utili: Compojure Doc

C'è anche " Noir " ( http://www.webnoir.org/ ), che è un nuovo framework web Clojure (così nuovo il i documenti non ci sono ancora). Provenendo da Django / Rails, scavo la sintassi semplice e diretta ed è piuttosto snella.

Considera il Web framework Luminus . Non ho affiliazioni ma ho sentito cose positive da amici che rispetto.

My current go-to web library is now yada.

If you are just starting out, the introductory server is Compojure. I see it as the apache of web servers in the Clojure world (in which case yada/aleph would be nginx). You could use Luminus as a template. There are variants of it, like compojure-api.

I tried ou Pedestal and was globally satisfied with it. I don't claim to master it, but it has a pleasant syntax, feels very cohesive, and looks like it does have great performance. It is also backed by Cognitect (the Clojure/Datomic company where Rich Hickey works).

I found Aleph to present an interesting abstraction, and the built-in backpressure seems interesting. I have yet to play with it, but it's definitely on my list.

After playing a bit with various web servers, here is my quick Pro/Cons list :

Short answer : have a look at Luminus to get started quickly, maybe move on to something else as your needs evolve (Yada maybe).

Compojure

  • Pros (1):

    • easy, lots of templates/examples (ex. Luminous)
  • Cons (2):

    • Not performant (a thread per request), expect performances slightly better than rails
    • Not simple, the middleware model has inconvenients

Pedestal

  • Pros (3):

    • interceptor model, pleasant syntax to add interceptors to a subset of routes
    • performant router
    • supports json/transit/multipart forms transparently out of the box, without asking anything. Very cool !
  • Cons (4):

    • no websocket support (yet), returning core.async channels would be nice
    • a bit slow to reload if putting it in a Stuart Sierra's component (I think you are supposed to use the reload interceptor)
    • no testing facility for async interceptors
    • requires buy-in (?)

Aleph

Pro (3):

  • Performant
  • backpressure
  • Websocket/SSE support when returning a manifold stream

Cons (1):

  • Low level, do it yourself style (ie. it just gives you a way to make your handlers do something. No router, no nothing). Not really a cons, just be aware of it.

Yada

Pro (3):

  • built on Aleph
  • content negociation
  • swagger integration
  • bidi is quite ok (though I like pedestal router syntax better)

Cons (1):

  • documentation (although not as bad as nginx-clojure, quickly improving).

HttpKit

Pro (2):

  • Written in Clojure ! (and Java...)
  • performance looks good (see the 600K concurrent connections post)

Cons (2):

  • No CORS support
  • Bugs ? Also, not a lot of recent commits

Nginx-Clojure

Note : I haven't played with it, mainly because of the lack of documentation. It looks interesting though, and very performant.

Pros (2):

  • Nginx (performant, offload ssl, restart workers...)
  • Could this model allow zero-downtime updates ? That would be so awesome !

Cons (1):

  • Documentation (improving). Also, I don't want to program in strings embedded in an nginx config file if that is the only way to do it.
  • Probably complicates a bit the first deployment (?)

Immutant

Note : I haven't played with it.

Pros :

  • integrated (caching, messaging, scheduling, wildfly deploy)

Cons :

  • no http client

Catacumba

Note : I haven't played with it, although the documentation looks excellent. I am probably going to try it next. There are example chat projects that look interesting, their heavy use of protocols put me off at first as a novice Clojure dev.

Pros (6):

  • documentation ! Like all funcool projects, the doc is very pleasant to read.
  • pedestal-like routing syntax
  • should be performant (on top of Ratpack)
  • backpressure
  • websockets, sse, cors, security, ssl...
  • unique features to dig : postal

Cons (2):

  • Not completely sure about how pleasant the ct/routes syntax is, and about ditching the Ring spec (supposedly for the async story, but I thought the pedestal guys fixed that)
  • Not sure how one would integrate swagger etc.
  • when I tried it, I was not able to make it work straight away

Note : a benchmark of Clojure web servers is available, if raw performance is all that matters.

These days Pedestal is a framework worth a look. It's a server-side framework that builds on top of Ring, but also frees the incoming request from the initial thread by being able to pause and resume that particular request (otherwise a slow request actually block that serverthread). Maybe sort of like a JavaBean.

Other cool frameworks are hoplon.io and David Nolen's Om (based on React)

Webjure, a web programming framework for Clojure.

Features: Dispatch servlet calls Clojure functions. Dynamic HTML generation. SQL query interface (through JDBC).

This answer is meant as a placeholder for Webjure information.

Compojure's what I used to build a tiny blogging application. It's modeled on Sinatra, which is a minimal, light-weight web framework for Ruby. I mostly just used the routing, which is just like Sinatra's. It looks like:

(GET "/post/:id/:slug"
  (some-function-that-returns-html :id :slug))

There's no ORM or templating library, but it does have functions that turn vectors into HTML.

You can also have look at these frameworks (taken from disclojure/projects):

There is also one more related question on Stack Overflow: Mature Clojure web frameworks?

Disclaimer: I am the author.

I put together a leiningen template which combines luminusweb and chestnut templates. So you get something that you can build clojure code with and clojurescript code for front and backend.
Additionally it provides user management plus some simple CRUD generation and some more small nice to haves: https://github.com/sveri/closp

I'll throw in my two cents for Duct, also from @weavejester, the maintainer of Compojure and Ring.

At it's core, it brings Component and the Ring router under one roof. Reasons why I use Duct:

  • Excellent philosophical foundation: it encourages you to build your app as a series of small components, and it strikes a nice balance between holding few opinions while providing sane defaults.
  • Stable path: I speak for myself, but over the years I've felt that the Clojure community has presented one less-than-credible web framework after another. A couple simply felt too experimental (my experience with Om and client-side Pedestal) for "getting things done" (not that they won't prove superior down the road). On the other hand, I feel like @weavejester has brought the same stability and measured progress to Duct that he did to Compojure and Ring, which have been superbly born out in the community.
  • It's super lightweight, and out of the way of my components.

Major features:

  • Organizes routes by "endpoints", small components that can you can think of as mini web servers (or, small cross sections of your HTTP routes).
  • Out-of-the-box support for the Reloaded Workflow.
  • Perfect integration with Ring and Compojure.
  • Development and production configurations (something I've found conspicuously missing elsewhere).
  • Good documentation with examples.

Note: It goes without saying, but for the benefit of web development newcomers, like most Clojurey things Duct requires a solid grasp of Clojure the language. I also recommend reading about Component first.

On another personal note, I've been using Duct in several production applications for over a year now and am extremely happy with it.

you can also try Clojure on Coils, http://github.com/zubairq/coils - disclaimer: I am the author

Another interesting webserver is Http-kit. It has good performance and is ring compliant, and has support for WebSockets as well. It is made mostly in clojure, and lacks some of the strange things in Jetty/Tomcat.

It's easy to tinker with.

Reframe and om.next probably what you are looking for.

Arachne is a newcomer web framework. Quoting the site's description:

Arachne is a full, highly modular web development framework for Clojure. It emphasizes ease, simplicity, and a solid, scalable design.

It has a kickstarter campaign claiming to offer a "getting started" experience similar to Rails. It is developed by a Cognitect.

Here is a good discussion about it with the author of Luminus (yogthos).

I've been using Liberator successfully in production for a while now. It's a great framework if you want just the bare bones e.g. if you're building a RESTful web service or something similar. It's essentially a wrapper for ring and compojure and provides a decision graph when validating incoming requests. It's also extremely fast compared to other more bulky web frameworks. If you want to start somewhere fast and slowly build out then Liberator is a great choice.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top