在開始之前我們需要準備一些環(huán)境屿附,以下為本次所需相關工具:
系統(tǒng):windows 7
JDK:1.8
開發(fā)工具:IntelliJ IDEA 2017.2.5
Maven:idea自帶最新版本腊徙,采用本地化setting.xml(可以參考阿里巴巴的源配置薛匪,這樣創(chuàng)建項目時自動下載要快很多倍)
本次編寫demo參考依據(jù)為Dropwizard官網(wǎng)
下面我們開始進入正題,創(chuàng)建第一個基于Dropwizard的Hello World
一勋磕、創(chuàng)建一個maven的web項目
這里在創(chuàng)建時因為我本地已經(jīng)存在了settings.xml悼枢,因此選擇本地化配置文件,如果采用默認的則不需要進行選擇综看。
點擊圖中標記的位置品腹,將相關包進行下載并加入引用中,其實默認就一個junit包引用而已红碑。
二舞吭、開始進行創(chuàng)建基礎包路徑
創(chuàng)建一個java目錄,并設置該目錄為根目錄析珊。
三羡鸥、在pom.xml中引入dependency基礎包。
<properties>
<dependency.version>1.2.0</dependency.version>
</properties>
<dependencies>
<!-- Dropwizard基礎包 -->
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>${dependency.version}</version>
</dependency>
</dependencies>
四忠寻、創(chuàng)建基礎yml配置文件
該demo1.yml文件中的內(nèi)容為:
#要打印的基礎語句惧浴,其中%s是占位符。
template: Hello, %s!
#默認引用時的名字奕剃,這里名字叫做Stranger
defaultName: Stranger
在這里開始進入Dropwizard特性的一些編寫了衷旅。
yml配置文件在官方解釋中是這樣說的:
Each Dropwizard application has its own subclass of the Configuration
class which specifies environment-specific parameters. These parameters are specified in a YAML configuration file which is deserialized to an instance of your application’s configuration class and validated.
The application we’ll be building is a high-performance Hello World service, and one of our requirements is that we need to be able to vary how it says hello from environment to environment. We’ll need to specify at least two things to begin with: a template for saying hello and a default name to use in case the user doesn’t specify their name.
因此我這里在寫hello world時就直接按照上面說的來了。word在模板里面先用占位符纵朋,這樣就可以[hello柿顶,小明]了o(╯□╰)o
五、創(chuàng)建基礎Configuration操软,用于進行反序列化嘁锯。
package com.demo1.helloworld.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import org.hibernate.validator.constraints.NotEmpty;
/**
* <b>TODO(com.demo1.helloworld.configuration @TODO)</b><br>
* 版權所有 <a >中國,華少</a><br>
* 本軟件僅對本次教程負責寺鸥,其版權歸屬cnHuaShao猪钮,如需引用,請申明其版權所有人胆建。
*
* @Description:
* @CreateDate 2017 2017/11/4 10:31 11 修改人:
* <a href="mailto:lz2392504@gmail.com">cnHuaShao</a>
* 修改備注:
* @since V1.0
*/
public class HelloWorldConfiguration extends Configuration {
/**
* NotEmpty注解表示該變量不可以為空烤低,之前我們在demo1.yml中已經(jīng)編寫了該變量對應的值,這個類主要是將其進行反序列化
*/
@NotEmpty
private String template;
/**
* NotEmpty注解表示該變量不可以為空笆载,之前我們在demo1.yml中已經(jīng)編寫了該變量對應的值扑馁,這個類主要是將其進行反序列化
* 默認值直接寫入Stranger涯呻,這里根據(jù)自己的demo1.yml中defaultName默認值寫的是什么就直接賦值什么,當然也可以不賦值腻要,等具體引用時在賦值复罐,不過建議還是寫上去一個默認值,防止它出錯雄家。
* 如果這兩個值是空效诅,則拋出系統(tǒng)異常
*/
@NotEmpty
private String defaultName = "Stranger";
/**
* 這里get set進行注解JsonProperty主要是為了對yml進行反序列化使用
* @return
*/
@JsonProperty
public String getTemplate() {
return template;
}
@JsonProperty
public void setTemplate(String template) {
this.template = template;
}
@JsonProperty
public String getDefaultName() {
return defaultName;
}
@JsonProperty
public void setDefaultName(String name) {
this.defaultName = name;
}
}
官方給出的解釋是:
Each Dropwizard application has its own subclass of the Configuration
class which specifies environment-specific parameters. These parameters are specified in a YAML configuration file which is deserialized to an instance of your application’s configuration class and validated.
The application we’ll be building is a high-performance Hello World service, and one of our requirements is that we need to be able to vary how it says hello from environment to environment. We’ll need to specify at least two things to begin with: a template for saying hello and a default name to use in case the user doesn’t specify their name.
六、進行創(chuàng)建基礎Application
package com.demo1.helloworld.application;
import com.demo1.helloworld.configuration.HelloWorldConfiguration;
import io.dropwizard.Application;
import io.dropwizard.setup.Environment;
/**
* <b>TODO(com.demo1.helloworld.application @TODO)</b><br>
* 版權所有 <a >中國趟济,華少</a><br>
* 本軟件僅對本次教程負責乱投,其版權歸屬cnHuaShao,如需引用顷编,請申明其版權所有人戚炫。
*
* @Description:
* @CreateDate 2017 2017/11/4 10:58 11 修改人:
* <a href="mailto:lz2392504@gmail.com">cnHuaShao</a>
* 修改備注:
* @since V1.0
*/
public class HelloWorldApplication extends Application<HelloWorldConfiguration> {
/**
* 基礎核心啟動方法。dropwizard應用的核心方法媳纬。主要進行處理具體的業(yè)務邏輯的類
* @param configuration
* @param environment
* @throws Exception
*/
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
}
@Override
public String getName() {
return "hello-world";
}
}
七双肤、創(chuàng)建一個基礎表示類,其需要使其轉(zhuǎn)成JSON時遵循RFC 1149
package com.demo1.helloworld.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.Length;
/**
* <b>TODO(com.demo1.helloworld.api @TODO)</b><br>
* 版權所有 <a >中國钮惠,華少</a><br>
* 本軟件僅對本次教程負責茅糜,其版權歸屬cnHuaShao,如需引用素挽,請申明其版權所有人限匣。
*
* @Description:
* @CreateDate 2017 2017/11/4 11:07 11 修改人:
* <a href="mailto:lz2392504@gmail.com">cnHuaShao</a>
* 修改備注:
* @since V1.0
*/
public class Saying {
private long id;
/**
* 內(nèi)容最大長度不可以超過10
*/
@Length(max = 10)
private String content;
public Saying() {
// Jackson deserialization
}
public Saying(long id, String content) {
this.id = id;
this.content = content;
}
@JsonProperty
public long getId() {
return id;
}
@JsonProperty
public String getContent() {
return content;
}
}
八、創(chuàng)建Resource 類
package com.demo1.helloworld.resources;
import com.codahale.metrics.annotation.Timed;
import com.demo1.helloworld.api.Saying;
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 java.util.concurrent.atomic.AtomicLong;
import java.util.Optional;
/**
* <b>TODO(com.demo1.helloworld.resources @TODO)</b><br>
* 版權所有 <a >中國毁菱,華少</a><br>
* 本軟件僅對本次教程負責,其版權歸屬cnHuaShao锌历,如需引用贮庞,請申明其版權所有人。
*
* @Description:
* @CreateDate 2017 2017/11/4 11:19 11 修改人:
* <a href="mailto:lz2392504@gmail.com">cnHuaShao</a>
* 修改備注:
* @since V1.0
*/
@Path("/hello-world")//跳轉(zhuǎn)地址
@Produces(MediaType.APPLICATION_JSON)//返回的數(shù)據(jù)類型
public class HelloWorldResource {
private final String template;
private final String defaultName;
private final AtomicLong counter;
public HelloWorldResource(String template, String defaultName) {
this.template = template;
this.defaultName = defaultName;
this.counter = new AtomicLong();
}
/**
* @Timed dropwizard會自動記錄時間和它的調(diào)用率作為度量定時器
* @param name
* @return
* @QueryParam 為URL鏈接后面的參數(shù)(url 究西?{參數(shù)名} = {參數(shù)值} 的格式)
*/
@GET//客戶端訪問時只能通過get方法訪問
@Timed
public Saying sayHello(@QueryParam("name") Optional<String> name) {
//如果name參數(shù)沒有傳入窗慎,則調(diào)用defaultName的值,如果傳入了卤材,則采用name的值
final String value = String.format(template, name.orElse(defaultName));
//返回Saying對象
return new Saying(counter.incrementAndGet(), value);
}
}
九遮斥、修改第六步時創(chuàng)建的Application中的run方法。
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
//聲明一個resource扇丛,并傳入初始化的值术吗,該值由configuration讀取的yml配置文件中的值。
//可以啟動多個resource
final HelloWorldResource resource = new HelloWorldResource(
configuration.getTemplate(),
configuration.getDefaultName()
);
environment.jersey().register(resource);
}
十帆精、創(chuàng)建一個HealthCheck類
package com.demo1.helloworld.health;
import com.codahale.metrics.health.HealthCheck;
/**
* <b>TODO(com.demo1.helloworld.health @TODO)</b><br>
* 版權所有 <a >中國较屿,華少</a><br>
* 本軟件僅對本次教程負責隧魄,其版權歸屬cnHuaShao,如需引用隘蝎,請申明其版權所有人购啄。
*
* @Description:
* @CreateDate 2017 2017/11/4 11:37 11 修改人:
* <a href="mailto:lz2392504@gmail.com">cnHuaShao</a>
* 修改備注:
* @since V1.0
*/
public class TemplateHealthCheck extends HealthCheck {
private final String template;
public TemplateHealthCheck(String template) {
this.template = template;
}
@Override
protected Result check() throws Exception {
final String saying = String.format(template, "模板測試");
if (!saying.contains("模板測試")) {
return Result.unhealthy("該模板不包含名稱");
}
return Result.healthy();
}
}
官方給出的解釋是這樣的:
Health checks give you a way of adding small tests to your application to allow you to verify that your application is functioning correctly in production. We strongly recommend that all of your applications have at least a minimal set of health checks.
其實這個是可有可無的,為了安全起見嘱么,這里先加上狮含。(官方例子中要求加上o(╯□╰)o)
十一、再次修改第六步時創(chuàng)建的Application中的run方法曼振。
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
//聲明一個resource几迄,并傳入初始化的值,該值由configuration讀取的yml配置文件中的值拴测。
//可以啟動多個resource
final HelloWorldResource resource = new HelloWorldResource(
configuration.getTemplate(),
configuration.getDefaultName()
);
//聲明一個檢查點乓旗,讓其進行檢查該模板的正確性。
final TemplateHealthCheck healthCheck =
new TemplateHealthCheck(configuration.getTemplate());
environment.healthChecks().register("template", healthCheck);
environment.jersey().register(resource);
}
十一集索、創(chuàng)建一個main方法屿愚。
package com.demo1.helloworld.main;
import com.demo1.helloworld.application.HelloWorldApplication;
/**
* <b>TODO(com.demo1.helloworld.main @TODO)</b><br>
* 版權所有 <a >中國,華少</a><br>
* 本軟件僅對本次教程負責务荆,其版權歸屬cnHuaShao妆距,如需引用,請申明其版權所有人函匕。
*
* @Description:
* @CreateDate 2017 2017/11/4 11:00 11 修改人:
* <a href="mailto:lz2392504@gmail.com">cnHuaShao</a>
* 修改備注:
* @since V1.0
*/
public class HelloWorldMain {
public static void main(String[] args) throws Exception {
//啟動helloworld
new HelloWorldApplication().run(args);
}
}
官方例子中main方法寫在Application類中娱据,我這里將其提出來了,方便大家理解盅惜。
至此中剩,我們這個例子基本上寫完了,開始進行打包抒寂。
十二结啼、修改maven的pom.xml文件
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<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>com.demo1.helloworld.main.HelloWorldMain</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
十三、開始進行打包
十四屈芜、開始啟動
看到上面的日志郊愧,則表明啟動成功,打開瀏覽器訪問:
http://localhost:8080/hello-world
http://localhost:8080/hello-world?name=xiaoming
至此井佑,本次的Hello World編寫完成属铁。
所有代碼均可以通過我的GItHub進行獲取到,如有需要可以點擊我的GitHub下載躬翁。