《Spring Boot in Action》【8. 部署】

8. 部署

8.1 部署到应用服务器

首先,我们构建一个war包:

apply plugin: 'war'

war {
    baseName = 'readinglist'
    version = '0.0.1-SNAPSHOT'
}

这样就能打成war包了,但目前这个war包没什么用,因为既没有包含web.xml也没有一个servlet initializer来enable Spring MVC的DispatcherServlet。这时候就需要用到SpringBootServletInitializer了,它是Spring的WebApplicationInitializer的一个实现,除了能配置DispatcherServlet,还能找到Filter、Servlet、ServletContextInitializer类型的beans,把它们绑定到servlet容器:

package readinglist;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

public class ReadingListServletInitializer extends SpringBootServletInitializer {
  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    return builder.sources(Application.class);
  }
}

configure方法里source了一个配置类,这个配置类就是Spring Boot的主配置来和启动类,实际上更简洁的做法是让Application类继承SpringBootServletInitializer就好了。

然后构建:

gradle build

war包就会在build/libs下面了,把它部署到Tomcat服务器就好了,当然,你仍然可以用java -jar运行:

java -jar readinglist-0.0.1-SNAPSHOT.war

8.2 生产数据库

开发的时候我们可以用自动配置的内置H2数据库,不过生产环境你就得用MySQL这样的数据库了:

---
spring:
  profiles: prod
  datasource:
    url: jdbc:mysql://localhost:3306/readinglist?useUnicode=true&characterEncoding=utf8
    username: ${MYSQL_USER}
    password: ${MYSQL_PASSWORD}

用户名和密码可以设置在系统环境变量里,防止密码暴露在代码里,要启用这段配置,要设置spring.profiles.active为prod,比较方便的做法是设置环境变量:

export SPRING_PROFILES_ACTIVE=prod

如果你使用Hibernate(JPA)和内置的H2数据库,Spring Boot会默认配置Hibernate自动创建数据库表,更具体地,它会设置Hibernate的hibernate.hbm2ddl.auto为create-drop,表明当Hibernate的SessionFactory创建完之后创建表,关闭的时候删除表。不过如果不使用内置的H2数据库,Spring Boot什么也不会做,表不会被创建,因此查询数据库的时候会报错,所以你要显示设置spring.jpa.hibernate.ddl-auto为create,create-drop或update,尽管设置为update看起来不错,不过在生产中并不推荐这么做,更好的做法是使用数据库迁移工具,Spring Boot为两种流行的工具提供了自动配置:

使用Flyway

使用SQL编写脚本,脚本都有版本号,Flyway会按顺序自动执行这些脚本,并将执行状态记录到数据库中防止重复执行。把脚本放在classpath根路径的/db/migration目录下(src/main/resources/db/migration),脚本命名方式是大写的“V”打头+一个版本号+双下划线+描述脚本用途的名字.sql,如V1__init.sql,当然你需要设置spring.jpa.hibernate.ddl-auto为none使得Hibernate不会自动创建表,最后引入flyway包即可:

compile("org.flywaydb:flyway-core")

当你启动应用的时候,flyway会根据schema_version表(会自动创建)中的脚本执行记录来执行db/migration中的脚本。

使用Liquibase

虽然Flyway用起来非常简单,不过用SQL脚本导致换一种数据库就无法工作了,Liquibase提供多种格式来编写脚本,包括XML、YAML和JSON,当然了,SQL也是支持的,引入Liquibase包:

compile("org.liquibase:liquibase-core")

默认情况下,liquibase的所有迁移脚本都写在/db/changelog目录下的db.changelog-master.yaml文件里,里面的每一块changeSet都有一个唯一id(不一定要是数字,任何文本都可以),脚本执行历史保存在databaseChangeLog表中,你可以修改默认的脚本位置:

liquibase:
  change-log: classpath:/db/changelog/db.changelog-master.xml

8.3 云端部署

8.3.1 部署到Cloud Foundry

Cloud Foundry是Pivotal公司的一个PaaS(Platform as a Service)平台,该公司是Spring生态系统的支持公司。

我们将要把应用部署到Pivotal Web Services(PWS),是Pivotal的一个公共Cloud Foundry平台。上去注册,有60天的试用期,从 https://console.run.pivotal.io/tools 下载并安装cf命令行工具,首先得登录:

$ cf login -a https://api.run.pivotal.io

部署:

$ cf push sbia-readinglist -p build/libs/readinglist.war

第一个参数是Cloud Foundry上的应用名称,并且会是应用的子域名 http://sbia-readinglist.cfapps.io。所以得确保唯一,不过你可以使用–random-route来随机生成一个子域名:

$ cf push sbia-readinglist -p build/libs/readinglist.war --random-route

不仅仅是WAR包,你也可以提供可执行JAR包,甚至是通过Spring Boot CLI运行的未编译的Groovy脚本。

重启应用:

$ cf restart

Cloud Foundry提供一系列服务,可以从marketplace找到,比如MySQL等,PostgreSQL服务在上面叫做elephantsql,有不同的套餐可以选择,查看套餐:

$ cf marketplace -s elephantsql

我们选择免费的turtle套餐,使用如下命令创建一个数据库服务:

$ cf create-service elephantsql turtle readinglistdb

服务创建完毕后,需要绑定到我们的应用:

$ cf bind-service sbia-readinglist readinglistdb

绑定服务只不过是通过VCAP_SERVICES环境变量来提供服务的连接信息,它并不会改变应用本身。我们不必修改应用,而是使用restage命令:

$ cf restage sbia-readinglist

cf restage命令使得Cloud Foundry重新部署应用并重新读取VCAP_SERVICES值。

8.3.2 部署到Heroku

Heroku使用不同的方式部署应用,它为你的应用维护Git仓库,每次你push代码,它会构建和部署应用。

首先你需要初始化你的项目目录作为Git仓库:

$ git init

这样就能使得Heroku命令行工具为你的项目自动添加远程Heroku Git仓库,然后使用apps:create命令在Heroku中建立应用:

$ heroku apps:create sbia-readinglist

上面的命令指定了项目的名称是sbia-readinglist,这个名字会作为Git仓库的名字以及应用的子域名,所以要确保名字唯一,或者你可以留空,这样Heroku会帮你生成一个唯一的名字。

apps:create命令会创建一个远程Git仓库 https://git.heroku.com/sbia-readinglist.git ,并且会在你的本地项目的Git配置中添加一个名为“heroku”的远程引用(可以用git remote -v查看),这样就可以用git命令push到Heroku了。

Heroku需要你提供一个名为Procfile的文件来告诉它如何运行应用,对于我们的reading-list应用来说,我们需要告诉Heroku用java命令来运行WAR包,假设我们用Gradle来构建,则需要在Procfile有一行:

web: java -Dserver.port=$PORT -jar build/libs/readinglist.war

Maven则是:

web: java -Dserver.port=$PORT -jar target/readinglist.war

你需要设置server.port为Heroku分配的端口(由$PORT变量提供)。

对于Gradle应用来讲,当Heroku试着构建应用的时候,它会执行stage任务,所以你需要在build.gradle中加入:

task stage(dependsOn: ['build']) {
}

它仅仅依赖了build任务,以便用stage任务来触发build。

你可能需要指定构建应用时的Java版本,最方便的方法是在项目根目录下建一个system.properties文件来设置:

java.runtime.version=1.7

接下来就可以push到Heroku了:

$ git commit -am "Initial commit"
$ git push heroku master

代码提交之后,Heroku会用Maven或Gradle构建应用,然后用Procfile中的指令运行,没问题的话你就可以访问应用了,比如 https://sbia-readinglist.herokuapp.com

然后,我们可以创建并绑定到一个PostgreSQL服务:

$ heroku addons:add heroku-postgresql:hobby-dev

这里我们选用了heroku-postgresql服务的免费的hobby-dev套餐,现在PostgreSQL已经创建并绑定到我们的应用了,并且Heroku会自动重启应用确保绑定成功。但此刻我们看/health接口,发现还是在使用内置的H2数据库,那是因为H2的自动配置仍然生效,我们并没有告诉Spring Boot去使用PostgreSQL。

一种选择是设置spring.datasource.*属性,我们可以使用如下命令查看数据库连接信息:

$ heroku addons:open waking-carefully-3728

其中waking-carefully-3728是我们的数据库实例的名字。这个命令会在浏览器中打开一个页面,里面有详细的数据库连接信息。

但是有一种更简单的方式,那就是使用Spring Cloud Connectors,它能和Cloud Foundry和Heroku一起工作,来发现绑定到应用的服务并自动配置应用使用这些服务。

我们只需要把它加入到依赖:

compile("org.springframework.boot:spring-boot-starter-cloud-connectors")

Spring Cloud Connectors只有在“cloud” profile激活的时候才会工作,在Heroku中激活“cloud” profile:

$ heroku config:set SPRING_PROFILES_ACTIVE="cloud"

然后就是push代码:

$ git commit -am "Add cloud connector"
$ git push heroku master

然后等应用启动完,再看/health接口,就会发现database已经变成了PostgreSQL。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring.Boot.in.Action.2015.12.pdfFor online information and ordering of this and other manning books, please visit www.manning.com.thepublisheroffersdiscountsonthisbookwhenorderedinquantity For more information, please contact Special sales department Manning publications co 20 Baldwin Road PO BoX 761 Shelter island. ny11964 Emailorders@manning.com @2016 by manning Publications Co. All rights reserved No part of this publication may be reproduced, stored in a retrieval system, or transmitted,in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and manning Publications was aware of a trademark claim, the designations have been printed in initial caps ll Recognizing the importance of preserving what has been written, it is Mannings policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine Manning publications co Development editor: Cynthia Kane 20 Baldwin Road Technical development editor: Robert casazza PO BoX 761 Copyeditor: Andy Carroll Shelter island. ny11964 Proofreader: Corbin Collins Technical p der John Guthrie Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN9781617292545 Printed in the united states of america 12345678910-EBM-201918171615 contents reword vii pre eface 2x about this book xii acknowledgments xu Bootstarting Spring I 1. 1 Spring rebooted Taking a fresh look at spring 2. Examining spring Boot essentials 4 What Spring Boot isn't 7 1.2 Getting started with Spring boot 8 Installing the spring boot cli 8 Initializing a spring boot project with Spring Initializr 12 3 Summary 22 Developing your first Spring Boot application 23 2.1 Putting spring boot to work 24 Examining a newly initialized spring boot project 26 Dissecting Bc iect build 30 2.2 USing starter dependencies 33 Specifying facet-based dependencies 34. Overriding starter transitive dependencies 35 CONTENTS 2.8 USing automatic configuration 37 Focusing on application functionality 37. Running the application 45. What just happened? 45 2.4 Summary 48 Customizing configuration 49 8.1 Overriding Spring Boot auto-configuration 50 Securing the application 50. Creating a custom security configuration 51. Taking another peek under the covers of auto-configuration55 8.2 Externalizing configuration with properties 57 Fine-tuning auto-configuration 58. Externally configuring application beans 64. Configuring with profiles 69 8.8 Customizing application error pages 71 3.4 Summary 74 Testing with Spring Boot 76 4.1 Integration testing auto-configuration 77 4.2 Testing web applications 79 Mocking spring MvC 80- Testing web security 83 4.3 Testing a running application 86 Starting the server on a random port 87. Testing HTML pages with selenium 88 4.4 Summary 90 Getting Groovy with the spring Boot CLI 92 5.1 Developing a Spring Boot CLI application 93 Setting up the cli project 93 Eliminating code noise with Groovy 94. What just happened? 98 5.2 Grabbing dependencies 100 Overriding default dependency versions 101. Adding dependency repositories 102 5.8 Running tests with the CLI 102 5.4 Creating a deployable artifact 105 5.5 Summary 106 CONTENTS 6 Applying Grails in Spring Boot 107 1 Using gorm for data persistence 108 2 Defining views with groovy server pages 113 6.3 Mixing spring boot with grails 3 115 Creating a new grails project 116 Defining the domain 118 Writing a grails controller 119. Creating the view 120 6.4 Summary 123 Taking a peek inside with the Actuator 124 7.1 Exploring the actuator's endpoints 125 Viewing configuration details 126. Tapping runtime metrics 133 Shutting down the application 139. Fetching application information 140 7.2 Connecting to the Actuator remote shell 141 Viewing the autoconfig report 142. Listing application beans 143 Watching application metrics 144.Invoking actuator endpoints 145 7. 3 Monitoring your application with JMX 146 7.4 Customizing the Actuator 148 Changing endpoint Ds 148 Enabling and disabling endpoints 149 Adding custom metrics and gauges 149- Creating a custom trace repository 153 Plugging in custom health indicators 155 7.5 Securing Actuator endpoints 156 7.6 Summary 159 8 Deploying Spring Boot applications 160 8.1 Weighing deployment options 161 8.2 Deploying to an application server 162 Building a WaRfile 162 Creating a production profile Enabling database migration 168 8.3 Pushing to the cloud 173 Deploying to Cloud Foundry 173 Deploying to Heroku 177 8. Summary 180 appendix a spring Boot developer Tools 187 appendix b spring Boot starters 188 appendix c Configuration properties 195 appendix d spring boot dependencies 232 index 243 In the spring of 2014, the Delivery Engineering team at Netflix set out to achieve a lofty goal: enable end-to-end global continuous delivery via a software platform that facilitates both extensibility and resiliency. my team had previously built two different applications attempting to address Netflix's delivery and deployment needs, but both were beginning to show the telltale signs of monolith-ness and neither met the goals of flexibility and resiliency. What's more, the most stymieing effect of these monolithic applications was ultimately that we were unable to keep pace with our partner's inno- vation. Users had begun to move around our tools rather than with them It became apparent that if we wanted to provide real value to the company and rap- idly innovate, we needed to break up the monoliths into small, independent services that could be released at will. Embracing a microservice architecture gave us hope that we could also address the twin goals of flexibility and resiliency. but we needed to do it on a credible foundation where we could count on real concurrency, legitimate moni- toring, reliable and easy service discovery, and great runtime performance With the jVM as our bedrock, we looked for a framework that would give us rapid velocity and steadfast operationalization out of the box. We zeroed in on Spring Boot Spring Boot makes it effortless to create Spring-powered, production-ready ser- vices without a lot of code! Indeed, the fact that a simple Spring Boot Hello World application can fit into a tweet is a radical departure from what the same functionality required on the vm only a few short years ago. Out-of-the-box nonfunctional features like security, metrics, health-checks, embedded servers, and externalized configura tion made boot an easy choice for us FOREWORD Yet, when we embarked on our Spring boot journey solid documentation was hard to come by. Relying on source code isnt the most joyful manner of figuring out how to properly leverage a frameworks features It's not surprising to see the author of mannings venerable Spring in Action take on the challenge of concisely distilling the core aspects of working with Spring Boot into another cogent book. Nor is it surprising that Craig and the Manning crew have done another tremendously wonderful job! Spring Boot in Action is an easily readable book, as weve now come to expect from Craig and manning From chapter Is attention-getting introduction to Boot and the now legend ary 9Oish-character tweetable Boot application to an in-depth analysis of Boots Actuator in chapter 7, which enables a host of auto-magical operational features required for any production application, Spring Boot in Action leaves no stone unturned. Indeed, for me, chapter 7's deep dive into the Actuator answered some of the lingering questions I've had in the back of my head since picking up Boot well over a year ago. Chapter 8s thor- ough examination of deployment options opened my eyes to the simplicity of cloud Foundry for cloud deployments. One of my favorite chapters is chapter 4, where Craig explores the many powerful options for easily testing a Boot application. From the get- o, I was pleasantly surprised with some of Springs testing features, and boot takes g advantage of them nicely As I've publicly stated before, Spring Boot is just the kind of framework the Java community has been seeking for over a decade. Its easy-to-use development features and out-of-the-box operationalization make java development fun again I,m pleased to report that Spring and spring boot are the foundation of Netflix's new continuous delivery platform. What's more, other teams at Netflix are following the same path because they too see the myriad benefits of boot It's with equal parts excitement and passion that I absolutely endorse craigs book as the easy-to-digest and fun-to-read Spring boot documentation the Java community has been waiting for since Boot took the community by storm. Craigs accessible writ- ing style and sweeping analysis of boot's core features and functionality will surely leave readers with a solid grasp of Boot(along with a joyful sense of awe for it) Keep up the great work Craig Manning Publications, and all the brilliant develop ers who have made spring boot what it is today each one of you has ensured a bright future for the JV ANDREW GLOVER MANAGER, DELIVERY ENGINEERING AT NETFLIX preface At the 1964 New York World's Fair, Walt Disney introduced three groundbreaking attractions:"“it' s a small world,”“ Great Moments with mr. Lincoln," and the“ Carouse of Progress " All three of these attractions have since moved into disneyland and walt Disney world, and you can still see them today My favorite of these is the Carousel of Progress. Supposedly, it was one of Walt Disneys favorites too. It's part ride and part stage show where the seating area rotates around a center area featuring four stages. Each stage tells the story of a family at different time periods of the 20th century-the early 1900s, the 1920s the 1940s, and recent times-highlighting the technology advances in that time period The story of innovation is told from a hand-cranked washing machine, to electric lighting and radio, to automatic dishwashers and television, to computers and voice-activated appliances In every act, the father (who is also the narrator of the show)talks about the latest inventions and says "It cant get any better only to discover that in fact, it does get better in the next act as technology progresses Although Spring doesn't have quite as long a history as that displayed in the Car- ousel of Progress, I feel the same way about Spring as"Progress Dad felt about the 20th century. Each and every Spring application seems to make the lives of developers so much better. Just looking at how Spring components are declared and wired together, we can see the following progression over the history of Spring
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值