一 Dropwizard是什么昔逗?
Dropwizard是一個(gè)跨越了庫(kù)和框架的界限备籽,他的目標(biāo)是提供一個(gè)生產(chǎn)就緒的web應(yīng)用程序所需的一切性能可靠的實(shí)現(xiàn)冀续。
(一)它主要包含以下組件:
1、Jetty for HTTP
將Jetty的http庫(kù)嵌入到項(xiàng)目中熔萧,不需要將我們的服務(wù)提交到復(fù)雜的服務(wù)器上糖驴。只需要一個(gè)main方法就可以啟動(dòng)服務(wù)。
2佛致、Jersey for REST
使用Jersey來(lái)支持ResJul風(fēng)格的web應(yīng)用的贮缕。它允許你編寫干凈的,可以測(cè)試的類俺榆,這個(gè)類可以優(yōu)雅的將http請(qǐng)求映射成為簡(jiǎn)單的Java對(duì)象
3感昼、Jackson for JSON
主要使用Jackson進(jìn)行JSON和Java對(duì)象轉(zhuǎn)換,方便快速罐脊。
4定嗓、Metrics for metrics
在生產(chǎn)環(huán)境中,Metrics為你提供獨(dú)一無(wú)二的洞察力萍桌,也就是說這個(gè)是用來(lái)監(jiān)控Java進(jìn)程的運(yùn)行狀態(tài)的
5宵溅、其他?
Logback,slf4j:日志類的庫(kù)?
Jdbi:連接關(guān)系型數(shù)據(jù)庫(kù)的工具類上炎。
?JodaTime:時(shí)間處理工具類?
Freemarker and Mustache:用戶界面模版?
Httpclient恃逻,JerseyClient:第三方接口通訊工具類。
(二)dropwizard優(yōu)勢(shì):
1藕施、更輕量寇损,不依賴外部的容器環(huán)境。
2铅碍、部署簡(jiǎn)單润绵,快速
3、約定優(yōu)于配置的思想胞谈,省卻了一些配置上的麻煩
4、代碼結(jié)構(gòu)良好,可讀性強(qiáng)
5烦绳、快速的項(xiàng)目引導(dǎo)
二 dropwizard使用步驟
使用dropwizard搭建服務(wù)的步驟:
1卿捎、創(chuàng)建maven工程
2、創(chuàng)建配置類
3径密、創(chuàng)建應(yīng)用類
4午阵、創(chuàng)建資源類
5、注冊(cè)資源類
6享扔、build工程
7底桂、運(yùn)行Jar
三 demo實(shí)例
1 創(chuàng)建maven工程,pom引用dropwizard dependency
pom:
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>1.2.0-rc1</version>
</dependency>
編譯配置:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration> <createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>application類路徑</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
2惧眠、創(chuàng)建配置類
package com.jasonlee.dropwizard.configuration;
import io.dropwizard.Configuration;
public class HelloWorldConfiguration extends Configuration {
private String template;
private String defaultName = "Stranger";
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
public String getDefaultName() {
return defaultName;
}
public void setDefaultName(String defaultName) {
this.defaultName = defaultName;
}
}
對(duì)應(yīng)的yml文件:
template: Hello, %s!
defaultName: Stranger
3籽懦、創(chuàng)建應(yīng)用類
package com.jasonlee.dropwizard.app;
import com.jasonlee.dropwizard.configuration.HelloWorldConfiguration;
import com.jasonlee.dropwizard.health.MyHealthCheck;
import com.jasonlee.dropwizard.resource.HelloServlet;
import com.jasonlee.dropwizard.resource.HelloWorldResource;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
public class HelloWorldApplication extends Application<HelloWorldConfiguration> {
public static void main(String[] args) throws Exception {
new HelloWorldApplication().run(args);//執(zhí)行run,此時(shí)run方法為空氛魁,待注冊(cè)資源
}
@Override
public String getName() {
return "hello-world";
}
@Override
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {
// nothing to do yet
}
@Override
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
//todo
}
}
4暮顺、創(chuàng)建資源類
package com.jasonlee.dropwizard.resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.codahale.metrics.annotation.Timed;
import com.google.common.base.Optional;
@Path("/hello-world")
@Produces(MediaType.APPLICATION_JSON)
public class HelloWorldResource {
private final String template;
private final String defaultName;
public HelloWorldResource(String template, String defaultName) {
this.template = template;
this.defaultName = defaultName;
}
@GET
@Timed
public String sayHello(@QueryParam("name") Optional<String> name) {
final String value = String.format(template, name.or(defaultName));
return value;
}
}
也可以直接創(chuàng)建servlet作為服務(wù)發(fā)布:
package com.jasonlee.dropwizard.resource;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("test over");
out.flush();
out.close();
}
}
可以創(chuàng)建健康檢查類供注冊(cè):
package com.jasonlee.dropwizard.health;
import com.codahale.metrics.health.HealthCheck;
public class MyHealthCheck extends HealthCheck {
private final String template;
public MyHealthCheck(String template) {
this.template = template;
}
@Override
protected Result check() throws Exception {
final String saying = String.format(template, "TEST");
if (!saying.contains("Hello")) {
return Result.unhealthy("template doesn't include a name");
}
return Result.healthy();
}
}
5、注冊(cè)資源類
在application的run方法中注冊(cè)上步創(chuàng)建的資源和servlet:
@Override
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
final HelloWorldResource resource = new HelloWorldResource(
configuration.getTemplate(),
configuration.getDefaultName()
);
environment.jersey().register(resource);
environment.getApplicationContext().addServlet(HelloServlet.class, "/test");
MyHealthCheck healthCheck =
new MyHealthCheck(configuration.getTemplate());
environment.healthChecks().register("template", healthCheck);
}
6秀存、build工程
在項(xiàng)目根目錄使用mv clean --mvn package進(jìn)行編譯或eclipse編譯捶码。
7運(yùn)行jar
java -jar jar路徑 server test.yml路徑
8 驗(yàn)證
訪問http://localhost:8080/hello-world/name=jasonlee可以訪問資源類發(fā)布的接口。
訪問http://localhost:8080/test可以訪問servlet發(fā)布的服務(wù)或链。
訪問http://localhost:8081可以查看metrics和health check等監(jiān)控信息惫恼。