Dropwizard是一个操作友好、开发RESTful服务的Java高性能框架,Dropwizard有自己独立的风格,可以辅助以Jetty Jackson Jersey和Metrics提供强大的基于JVM后端服务,Dropwizard将稳定 成熟带给了Java生态系统,大道至简,轻量库包让你聚焦业务,Dropwizard有out-of-the-box支持复杂的配置 应用度量记录、日志等,让你的队伍在短时间内生产出高质量的HTTP+JSON Web服务。
https://www.jdon.com/soa/6-restful.html
配置文件time-service.yml
defaultTimezone: UTC
server:
applicationConnectors:
- type: http
port: 9000
adminConnectors:
- type: http
port: 9001
配置文件封装类
package com.zte.sunquan.demo.wizard;
import io.dropwizard.Configuration;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by 10184538 on 2018/9/8.
*/
public class TimeZoneConfigure extends Configuration {
@NotEmpty
@JsonProperty
private String defaultTimezone;
public String getDefaultTimezone() {
return defaultTimezone;
}
}
主体请求处理逻辑
package com.zte.sunquan.demo.wizard;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
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.google.common.base.Optional;
/**
* Created by 10184538 on 2018/9/8.
*/
@Path("/time")
@Produces(MediaType.APPLICATION_JSON)
public class TimeResource {
private final String defaultTimezone;
public TimeResource(String defaultTimezone) {
this.defaultTimezone = defaultTimezone;
}
@GET
public Time getTime(@QueryParam("timezone") Optional timezone) {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("配置文件中配置:" + defaultTimezone);//配置文件中配置
TimeZone timeZone = null;
if (timezone.isPresent()) {
timeZone = TimeZone.getTimeZone(timezone.get().toString());
System.out.println("请求中配置:" + timezone.get().toString());
} else {
timeZone = TimeZone.getTimeZone(defaultTimezone);
}
formatter.setTimeZone(timeZone);
String formatted = formatter.format(new Date());
return new Time(formatted);
}
}
启动类
package com.zte.sunquan.demo.wizard;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
/**
* Created by 10184538 on 2018/9/8.
*/
public class TimeApplication extends Application<TimeZoneConfigure> {
public static void main(String[] args) throws Exception {
new TimeApplication().run(args);
}
@Override
public void initialize(Bootstrap timezoneConfigurationBootstrap) {
}
@Override
public void run(TimeZoneConfigure timeZoneConfigure, io.dropwizard.setup.Environment environment) throws Exception {
final TimeResource resource = new TimeResource(timeZoneConfigure.getDefaultTimezone());
environment.jersey().register(resource);
}
}
注意dropwizard需要传入配置文件:
http://localhost:9000/time?timezone=MST
输出:
{"time":"2018-09-08 08:47:15"}
输出:
{"time":"2018-09-08 01:47:53"}