dropwizard微服务实践

一 Dropwizard是什么?
Dropwizard是一个跨越了库和框架的界限,他的目标是提供一个生产就绪的web应用程序所需的一切性能可靠的实现。
(一)它主要包含以下组件:
1、Jetty for HTTP
将Jetty的http库嵌入到项目中,不需要将我们的服务提交到复杂的服务器上。只需要一个main方法就可以启动服务。
2、Jersey for REST
使用Jersey来支持ResJul风格的web应用的。它允许你编写干净的,可以测试的类,这个类可以优雅的将http请求映射成为简单的Java对象
3、Jackson for JSON
主要使用Jackson进行JSON和Java对象转换,方便快速。
4、Metrics for metrics
在生产环境中,Metrics为你提供独一无二的洞察力,也就是说这个是用来监控Java进程的运行状态的
5、其他•
Logback,slf4j:日志类的库•
Jdbi:连接关系型数据库的工具类。
•JodaTime:时间处理工具类•
Freemarker and Mustache:用户界面模版•
Httpclient,JerseyClient:第三方接口通讯工具类。

(二)dropwizard优势:
1、更轻量,不依赖外部的容器环境。
2、部署简单,快速
3、约定优于配置的思想,省却了一些配置上的麻烦
4、代码结构良好,可读性强
5、快速的项目引导

二 dropwizard使用步骤
使用dropwizard搭建服务的步骤:
1、创建maven工程
2、创建配置类
3、创建应用类
4、创建资源类
5、注册资源类
6、build工程
7、运行Jar

三 demo实例
1 创建maven工程,pom引用dropwizard dependency
pom:


     io.dropwizard
     dropwizard-core
        1.2.0-rc1

编译配置:

 
    
        
            org.apache.maven.plugins
            maven-shade-plugin
            2.3
                       true
                
                    
                        *:*
                        
                            META-INF/*.SF
                            META-INF/*.DSA
                            META-INF/*.RSA
                        
                    
                
            
            
                
                    package
                    
                        shade
                    
                    
                        
                            
                            
                                application类路径
                            
                        
                    
                
            
        
        
            org.apache.maven.plugins
            maven-compiler-plugin
            
                1.8
                1.8
            
        

    

2、创建配置类

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;
       }
}

对应的yml文件:

template: Hello, %s!
defaultName: Stranger

3、创建应用类

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 {
    public static void main(String[] args) throws Exception {
        new HelloWorldApplication().run(args);//执行run,此时run方法为空,待注册资源
    }

    @Override
    public String getName() {
        return "hello-world";
    }

    @Override
    public void initialize(Bootstrap bootstrap) {
        // nothing to do yet
    }

    @Override
    public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
        //todo
    }
}

4、创建资源类

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 name) {
            final String value = String.format(template, name.or(defaultName));
            return value;
        }
}

也可以直接创建servlet作为服务发布:

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();
          }
}

可以创建健康检查类供注册:

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、注册资源类
在application的run方法中注册上步创建的资源和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工程
在项目根目录使用mv clean --mvn package进行编译或eclipse编译。
7运行jar
java -jar jar路径 server test.yml路径

8 验证
访问http://localhost:8080/hello-world/name=jasonlee可以访问资源类发布的接口。
访问http://localhost:8080/test可以访问servlet发布的服务。
访问http://localhost:8081可以查看metrics和health check等监控信息。

你可能感兴趣的:(dropwizard微服务实践)