使用Spring Boot快速构建应用

微服务(Microservice)架构

  1. 什么是微服务架构?

微服务是指开发一个单个 小型的但有业务功能的服务,每个服务都有自己的处理和轻量通讯机制,可以部署在单个或多个服务器上。
微服务也指一种种松耦合的、有一定的有界上下文的面向服务架构。也就是说,如果每个服务都要同时修改,那么它们就不是微服务,因为它们紧耦合在一起;如果你需要掌握一个服务太多的上下文场景使用条件,那么它就是一个有上下文边界的服务,这个定义来自DDD领域驱动设计。

  1. 微服务优点是什么?

每个微服务都很小,这样能聚焦一个指定的业务功能或业务需求。
微服务能够被小团队单独开发,这个小团队是2到5人的开发人员组成。
微服务是松耦合的,是有功能意义的服务,无论是在开发阶段或部署阶段都是独立的。
微服务能使用不同的语言开发。
微服务允许容易且灵活的方式集成自动部署,通过持续集成工具,如Jenkins, Hudson, bamboo 。
一个团队的新成员能够更快投入生产。
微服务易于被一个开发人员理解,修改和维护,这样小团队能够更关注自己的工作成果。无需通过合作才能体现价值。
微服务允许你利用融合最新技术。
微服务只是业务逻辑的代码,不会和HTML,CSS 或其他界面组件混合。
微服务能够即时被要求扩展。
微服务能部署中低端配置的服务器上。
易于和第三方集成。
每个微服务都有自己的存储能力,可以有自己的数据库。也可以有统一数据库。

  1. 微服务架构的缺点是什么?

微服务架构可能带来过多的操作。
需要DevOps技巧 (http://en.wikipedia.org/wiki/DevOps).
可能双倍的努力。
分布式系统可能复杂难以管理。
因为分布部署跟踪问题难。
当服务数量增加,管理复杂性增加。

  1. 微服务适合哪种情况?

当你需要支持桌面 web 移动 智能电视 可穿戴时都是可以的,甚至将来你可能不知道但需要支持的某种环境。

  1. 哪个公司或产品使用微服务架构?

大部分大型网站系统如Twitter, Netflix, Amazon 和 eBay都已经从传统整体型架构monolithic architecture迁移到微服务架构

  1. 微服务之间是如何独立通讯的?

这依赖需求,通过使用HTTP/REST,数据格式使用JSON 或 Protobuf(Binary protocol),通讯协议是自由的。

Spring Boot 微服务

Spring 4倡导微服务的架构,针对这一理念,近来在微博上也有一些有价值的讨论。微服务架构倡导将功能拆分到离散的服务中,独立地进行部署,Spring Boot能够很方便地将应用打包成独立可运行的JAR包,因此在开发模式上很契合这一理念。
随着Spring 4新版本的发布,Spring Boot这个新的子项目得到了广泛的关注,因为不管是Spring 4官方发布的新闻稿还是针对首席架构师Adrian Colyer的专访,都对这个子项目所带来的生产率提升赞誉有加。
Spring Boot充分利用了JavaConfig的配置模式以及“约定优于配置”的理念,能够极大的简化基于Spring MVC的Web应用和REST服务开发。

Hello Spring Boot应用实例

现在企业级的Java web项目应该或多或少都会使用到Spring框架的。

回首我们以前使用Spring框架的时候,我们需要首先在(如果你使用Maven的话)pom文件中增加对相关的的依赖(使用gradle来构建的话基本也一样)然后新建Spring相关的xml文件,而且往往那些xml文件还不会少。然后继续使用tomcat或者jetty作为容器来运行这个工程。基本上每次创建一个新的项目都是这么一个流程,而我们有时候仅仅想快速的创建一个Spring web工程来测试一些东西,或者是希望能节省时间。

现在我们使用Spring Boot就可以快速的做到这些了。

详细代码参考:https://github.com/wtclosyn/repostories/tree/master/SimpleSpringBoot

Spring Contoller
package com.losyn.hello.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Hello Wold Controller
 */
@Controller
@RequestMapping("/")
public class HelloController {

    @RequestMapping(value ="/hello", method = RequestMethod.GET)
    public @ResponseBody String helloWold(){
        return "Hello Wold!!!";
    }
}
Spring Boot主程序
package com.losyn.hello;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * SpringBoot 主程序
 */
@SpringBootApplication
public class HelloApplication implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }

    public void run(String... args) throws Exception {
        System.out.println("input Ctrl-C to end this application");
        Thread.currentThread().join();
    }
}
pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>hispringboot</groupId>
    <artifactId>hispringboot</artifactId>
    <name>The Spring Boot Hello Wold</name>
    <packaging>jar</packaging>
    <version>1.0.0</version>

    <properties/>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.2.3.RELEASE</version>
        </dependency>
    </dependencies>

</project>

Spring Boot就这么简单,一个Hello Wold Web应用开发好了

直接运行 HelloApplication.java 中的 main 方法

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.2.3.RELEASE)

2015-04-25 23:29:13.484  INFO 7960 --- [           main] com.losyn.hello.HelloApplication         : Starting HelloApplication on Losyn-PC with PID 7960 (C:\GitRepository\SimpleSpringBoot\target\classes started by Administrator in C:\GitRepository)
2015-04-25 23:29:13.535  INFO 7960 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@77ec78b9: startup date [Sat Apr 25 23:29:13 CST 2015]; root of context hierarchy
2015-04-25 23:29:14.976  INFO 7960 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2015-04-25 23:29:16.072  INFO 7960 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2015-04-25 23:29:16.344  INFO 7960 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2015-04-25 23:29:16.346  INFO 7960 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.20
2015-04-25 23:29:16.530  INFO 7960 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2015-04-25 23:29:16.530  INFO 7960 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2999 ms
2015-04-25 23:29:17.515  INFO 7960 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2015-04-25 23:29:17.528  INFO 7960 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2015-04-25 23:29:17.529  INFO 7960 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2015-04-25 23:29:17.928  INFO 7960 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@77ec78b9: startup date [Sat Apr 25 23:29:13 CST 2015]; root of context hierarchy
2015-04-25 23:29:18.017  INFO 7960 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[//hello],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.losyn.hello.controller.HelloController.helloWold()
2015-04-25 23:29:18.019  INFO 7960 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2015-04-25 23:29:18.019  INFO 7960 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2015-04-25 23:29:18.053  INFO 7960 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-04-25 23:29:18.053  INFO 7960 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-04-25 23:29:18.103  INFO 7960 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-04-25 23:29:18.205  INFO 7960 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2015-04-25 23:29:18.344  INFO 7960 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
input Ctrl-C to end this application

会产生上面的输出,查看日志可以发现默认使用的是tomcat,端口绑定在8080,现在让我们来访问:http://localhost:8080/hello 就可以看到页面显示“Hello Wold!!!”。

posted @ 2015-04-25 23:34  二进制世界  阅读(538)  评论(0)    收藏  举报