SpringBoot-cors,https,eureka,zuul,configuration,docker,hystrix
跨源资源共享(CORS)是一种安全概念,允许限制在Web浏览器中实现的资源.它可以防止JavaScript代码产生或消耗不同来源的请求.
例如,您的Web应用程序在8080端口上运行,并且使用JavaScript尝试从9090开始使用RESTful Web服务港口.在这种情况下,您将在Web浏览器上面临跨源资源共享安全问题.
处理此问题需要两个要求 :
-
RESTful Web服务应该支持跨源资源共享.
-
RESTful Web服务应用程序应该允许从8080端口访问API.
在本章中,我们将详细了解如何为RESTful Web服务应用程序启用跨源请求.
在控制器方法中启用CORS
我们需要设置RESTful Web服务的来源通过对控制器方法使用 @CrossOrigin 注释. @CrossOrigin注释支持特定的REST API,而不支持整个应用程序.
@RequestMapping(value = "/products") @CrossOrigin(origins = "http://localhost:8080") public ResponseEntity<Object> getProduct() { return null; }
全局CORS配置
我们需要定义显示的@Bean配置来设置CORS全局配置支持你的Spring Boot应用程序.
@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/products").allowedOrigins("http://localhost:9000"); } }; }
下面给出了在主Spring Boot应用程序中全局设置CORS配置的代码.
package com.it1352.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/products").allowedOrigins("http://localhost:8080"); } }; } }
现在,您可以创建一个在8080端口上运行的Spring Boot Web应用程序和您的RESTful Web服务应用程序可以在9090端口上运行.
启用HTTPS
默认情况下,Spring Boot应用程序在应用程序启动时使用HTTP 8080端口.
您需要按照下面给出的步骤在Spring Boot应用程序中配置HTTPS和端口443 :
-
获取SSL证书 - 创建自签名证书或从证书颁发机构获取证书
-
启用HTTPS和443端口
自签名证书
要创建自签名证书,Java Run Time环境与证书管理实用程序密钥工具捆绑在一起.此实用程序工具用于创建自签名证书.它显示在这里给出的代码中 :
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650 Enter keystore password: Re-enter new password: What is your first and last name? [Unknown]: What is the name of your organizational unit? [Unknown]: What is the name of your organization? [Unknown]: What is the name of your City or Locality? [Unknown]: What is the name of your State or Province? [Unknown]: What is the two-letter country code for this unit? [Unknown]: Is CN = Unknown, OU=Unknown, O = Unknown, L = Unknown, ST = Unknown, C = Unknown correct? [no]: yes
此代码将生成一个名为keystore.p12的PKCS12密钥库文件,证书别名为tomcat.
配置HTTPS
我们需要提供服务器端口443,密钥存储文件路径,密钥存储密码,密钥存储类型和密钥别名到application.properties文件中.观察此处给出的代码 :
server.port: 443 server.ssl.key-store: keystore.p12 server.ssl.key-store-password: springboot server.ssl.keyStoreType: PKCS12 server.ssl.keyAlias: tomcat
如果您使用以下代码,则可以使用以下代码:application.yml :
server: port: 443 ssl: key-store: keystore.p12 key-store-password: springboot keyStoreType: PKCS12 keyAlias: tomcat
您可以创建一个可执行的JAR文件,并使用以下Maven或Gradle命令运行spring boot应用程序.
对于Maven,你可以使用以下命令 :
mvn clean install
之后"BUILD SUCCESS",你可以在目标目录下找到JAR文件.
F或者Gradle,你可以使用命令
gradle clean build
在"BUILD SUCCESSFUL"之后,您可以在build/libs目录下找到JAR文件.
现在,使用以下命令运行JAR文件 :
java -jar <JARFILE>
现在,应用程序已在Tomcat端口443上启动,其中https显示为 :
Spring Boot - Eureka Server
Eureka Server是一个包含所有客户端服务应用程序信息的应用程序.每个Micro服务都将注册到Eureka服务器,Eureka服务器知道在每个端口和IP地址上运行的所有客户端应用程序. Eureka Server也称为Discovery Server.
在本章中,我们将详细了解如何构建Eureka服务器.
建立一个Eureka Server
Eureka Server随附Spring Cloud捆绑包.为此,我们需要开发Eureka服务器并在默认端口8761上运行.
访问Spring Initializer主页 https://start.spring.io/并下载具有Eureka服务器依赖性的Spring Boot项目.它显示在下面的屏幕截图中 :
在主Spring Boot Application类文件中下载项目后,我们需要添加@EnableEurekaServer注释. @EnableEurekaServer注释用于使您的Spring Boot应用程序充当Eureka服务器.
主Spring Boot应用程序类文件的代码如下所示 :
package com.it1352.eurekaserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaserverApplication { public static void main(String[] args) { SpringApplication.run(EurekaserverApplication.class, args); } }
确保在构建配置文件中添加了Spring cloud Eureka服务器依赖项.
Maven用户依赖的代码如下所示 :
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency>
Gradle用户依赖的代码低于 :
compile('org.springframework.cloud:spring-cloud-starter-eureka-server')
完整的构建配置文件在下面给出 :
Maven 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>com.IT屋</groupId> <artifactId>eurekaserver</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>eurekaserver</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Gradle - build.gradle
buildscript { ext { springBootVersion = '1.5.9.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.it1352' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = 'Edgware.RELEASE' } dependencies { compile('org.springframework.cloud:spring-cloud-starter-eureka-server') testCompile('org.springframework.boot:spring-boot-starter-test') } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } }
默认情况下,Eureka Server注册本身进入发现.您应该将以下给定的配置添加到application.properties文件或application.yml文件中.
application.properties文件在下面给出 :
eureka.client.registerWithEureka = false eureka.client.fetchRegistry = false server.port = 8761
application.yml文件在下面给出 :
eureka: client: registerWithEureka: false fetchRegistry: false server: port: 8761
现在,您可以创建一个可执行的JAR文件,使用下面显示的Maven或Gradle命令运行Spring Boot应用程序 :
对于Maven,使用如下所示的命令 :
mvn clean install
在"BUILD SUCCESS"之后,您可以在目标目录下找到JAR文件.
对于Gradle,您可以使用t他的命令显示如下 :
gradle clean build
之后" "BUILD SUCCESSFUL",你可以在build/libs目录下找到JAR文件.
现在,使用以下命令运行JAR文件 :
java -jar <JARFILE>
你可以发现应用程序已经在Tomcat端口8761上启动,如下所示 :
现在,点击URL http://localhost:8761/在您的Web浏览器中,您可以找到在端口8761上运行的Eureka Server,如下所示 :
在本章中,您将详细了解如何将Spring Boot Micro服务应用程序注册到Eureka Server.在注册应用程序之前,请确保Eureka Server在端口8761上运行或首先构建Eureka Server并运行它.有关构建Eureka服务器的更多信息,请参阅上一章.
首先,您需要在我们的构建配置文件中添加以下依赖项,以便使用Eureka服务器注册微服务.
Maven用户可以将以下依赖项添加到 pom.xml 文件中 :
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency>
Gradle用户可以将以下依赖项添加到 build.gradle 文件 :
compile('org.springframework.cloud:spring-cloud-starter-eureka')
现在,我们需要在主Spring Boot应用程序类文件中添加@EnableEurekaClient批注. @EnableEurekaClient注释使您的Spring Boot应用程序充当Eureka客户端.
主要的Spring Boot应用程序如下所示 :
package com.it1352.eurekaclient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient public class EurekaclientApplication { public static void main(String[] args) { SpringApplication.run(EurekaclientApplication.class, args); } }
要将Spring Boot应用程序注册到Eureka Server,我们需要在application.properties文件中添加以下配置或者application.yml文件并在我们的配置中指定Eureka Server URL.
application.yml文件的代码在下面给出 :
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka instance: preferIpAddress: true spring: application: name: eurekaclient
application.properties文件的代码在下面和下面给出;
eureka.client.serviceUrl.defaultZone = http://localhost:8761/eureka eureka.client.instance.preferIpAddress = true spring.application.name = eurekaclient
现在,在主Spring Boot应用程序中添加Rest Endpoint以返回String和构建配置文件中的Spring Boot Starter Web依赖项.观察下面给出的代码 :
package com.it1352.eurekaclient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @EnableEurekaClient @RestController public class EurekaclientApplication { public static void main(String[] args) { SpringApplication.run(EurekaclientApplication.class, args); } @RequestMapping(value = "/") public String home() { return "Eureka Client application"; } }
整个配置文件如下:
对于Maven用户 - 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>com.IT屋</groupId> <artifactId>eurekaclient</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>eurekaclient</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </projecta>
对于Gradle用户 - build.gradle
buildscript { ext { springBootVersion = '1.5.9.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.IT屋' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = 'Edgware.RELEASE' } dependencies { compile('org.springframework.cloud:spring-cloud-starter-eureka') testCompile('org.springframework.boot:spring-boot-starter-test') compile('org.springframework.boot:spring-boot-starter-web') } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } }
您可以创建一个可执行的JAR文件,并使用以下Maven或Gradle命令运行Spring Boot应用程序 :
For Maven ,你可以使用以下命令 :
mvn clean install
在"BUILD SUCCESS"之后,您可以在目标目录下找到JAR文件.
对于Gradle,您可以使用以下命令 :
gradle clean build
在"BUILD SUCCESSFUL"之后,你可以在build/libs目录下找到JAR文件.
现在,使用如下所示的命令运行JAR文件 :
java –jar <JARFILE>
现在,应用程序已在Tomcat端口8080上启动,Eureka Client应用程序已在Eureka Server上注册,如下所示 :
点击URL http://localhost:8761/在你的网页浏览器,您可以看到Eureka客户端应用程序已在Eureka Server注册.
现在在网络浏览器中点击URL http://localhost:8080/并查看Rest Endpoint输出.
Zuul Server是一个网关应用程序,可处理所有请求并执行微服务应用程序的动态路由. Zuul服务器也称为边缘服务器.
例如,/api/user 映射到用户服务,/api/products映射到产品服务和Zuul Server动态地将请求路由到相应的后端应用程序.
在本章中,我们将详细介绍如何在Spring Boot中创建Zuul Server应用程序.
创建Zuul服务器应用程序
Zuul服务器捆绑了Spring Cloud依赖项.您可以从Spring Initializer页面下载Spring Boot项目 https://start.spring.io/并选择Zuul Server依赖项.
添加主Spring Boot应用程序上的@EnableZuulProxy注释. @EnableZuulProxy注释用于使您的Spring Boot应用程序充当Zuul代理服务器.
package com.it1352.zuulserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringBootApplication @EnableZuulProxy public class ZuulserverApplication { public static void main(String[] args) { SpringApplication.run(ZuulserverApplication.class, args); } }
您必须在我们的构建配置文件中添加Spring Cloud Starter Zuul依赖项.
Maven用户必须在 pom.xml 文件中添加以下依赖项 :
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency>
对于Gradle用户,在build.gradle文件中添加以下依赖项
compile('org.springframework.cloud:spring-cloud-starter-zuul')
对于Zuul路由,在应用程序中添加以下属性.properties文件或application.yml文件.
spring.application.name = zuulserver zuul.routes.products.path = /api/demo/** zuul.routes.products.url = http://localhost:8080/ server.port = 8111
这意味着对/api/demo/的http调用会转发到产品服务.例如,/api/demo/products 转发到/products .
yaml文件用户可以使用application.yml文件如下所示 :
server: port: 8111 spring: application: name: zuulserver zuul: routes: products: path: /api/demo/** url: http://localhost:8080/
注意 : 在通过Zuul Proxy进行路由之前, http://localhost:8080/应用程序应该已经运行.
完整的构建配置文件如下所示.
Maven用户可以使用下面给出的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>com.IT屋</groupId> <artifactId>zuulserver</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>zuulserver</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Gradle用户可以使用下面给出的build.gradle文件 :
buildscript { ext { springBootVersion = '1.5.9.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.IT屋' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = 'Edgware.RELEASE' } dependencies { compile('org.springframework.cloud:spring-cloud-starter-zuul') testCompile('org.springframework.boot:spring-boot-starter-test') } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } }
你可以创建一个可执行的JAR文件,并使用下面给出的Maven或Gradle命令运行Spring Boot应用程序 :
对于Maven,您可以使用下面给出的命令 :
mvn clean install
在"BUILD SUCCESS"之后,您可以在下面找到JAR文件目标目录.
对于Gradle,您可以使用下面给出的命令 :
gradle clean build
在"BUILD SUCCESSFUL"之后,你可以在build/libs目录下找到JAR文件.
现在,使用下面显示的命令运行JAR文件 :
java -jar <JARFILE>
您可以在Tomcat端口8111上找到已启动的应用程序,如下所示.
现在,点击URL http://localhost:8111/api/demo/products 在您的网络浏览器中,您可以看到/products REST端点的输出,如下所示 :
Spring Cloud Configuration Server是一个集中式应用程序,可管理所有与应用程序相关的配置属性.在本章中,您将详细了解如何创建Spring Cloud Configuration服务器.
创建Spring Cloud配置服务器
首先,下载Spring从Spring Initializer页面启动项目并选择Spring Cloud Config Server依赖项.观察下面给出的截图 :
现在,在构建配置文件中添加Spring Cloud Config服务器依赖项,如下所述 :
Maven用户可以将以下依赖项添加到pom.xml文件中.
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
Gradle用户可以在build.gradle文件中添加以下依赖项.
compile('org.springframework.cloud:spring-cloud-config-server')
现在,在主Spring中添加@EnableConfigServer注释启动应用程序类文件. @EnableConfigServer注释使您的Spring Boot应用程序充当配置服务器.
主要的Spring Boot应用程序类文件在下面和下面给出;
package com.it1352.configserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; @SpringBootApplication @EnableConfigServer public class ConfigserverApplication { public static void main(String[] args) { SpringApplication.run(ConfigserverApplication.class, args); } }
现在,将以下配置添加到属性文件中,并将application.properties文件替换为bootstrap.properties文件.观察下面给出的代码 :
server.port = 8888 spring.cloud.config.server.native.searchLocations=file:///C:/configprop/ SPRING_PROFILES_ACTIVE=native
Configuration Server在Tomcat端口8888上运行,应用程序配置属性从本机加载搜索位置.
现在,在 file:///C:/configprop/中,放置客户端应用程序 - application.properties文件.例如,您的客户端应用程序名称是 config-client ,然后将您的application.properties文件重命名为 config-client.properties ,并将属性文件放在路径上file:///C:/configprop/.
config-client属性文件的代码在下面给出 :
welcome.message = Welcome to Spring cloud config server
完整的构建配置文件在下面和下面给出;
Maven用户可以使用下面给出的 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>com.IT屋</groupId> <artifactId>configserver</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>configserver</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Gradle用户可以使用下面给出的build.gradle文件 :
<scope>import</scope> </dependency> </dependencies> buildscript { ext { springBootVersion = '1.5.9.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.it1352' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = 'Edgware.RELEASE' } dependencies { compile('org.springframework.cloud:spring-cloud-config-server') testCompile('org.springframework.boot:spring-boot-starter-test') } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } }
现在,创建一个可执行的JAR文件,并使用以下Maven或Gradle命令运行Spring Boot应用程序 :
对于Maven,使用下面给出的命令 :
mvn clean install
在"BUILD SUCCESS"之后,您可以在目标目录下找到JAR文件.
对于Gradle,使用下面给出的命令 :
gradle clean build
在"BUILD SUCCESSFUL"之后,您可以在build/libs目录下找到JAR文件.
使用运行JAR文件以下命令 :
java -jar <JARFILE>
现在,应用程序已在Tomcat端口8888上启动,如下所示 :
现在点击URL http://localhost:8888/config-client/default/master 在您的Web浏览器上,您可以看到您的config-client应用程序配置属性,如下所示.
某些应用程序可能需要可能需要更改的配置属性,开发人员可能需要将其关闭或重新启动应用程序才能执行此操作.但是,这可能会导致生产停机并需要重新启动应用程序. Spring Cloud Configuration Server允许开发人员加载新的配置属性,而无需重新启动应用程序,也不会出现任何停机.
使用Spring Cloud Configuration Server
首先,从 https://start.spring.io/下载Spring Boot项目并选择Spring云配置客户端依赖项.现在,在构建配置文件中添加Spring Cloud Starter Config依赖项.
Maven用户可以将以下依赖项添加到pom.xml文件中.
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
Gradle用户可以将以下依赖项添加到 build.gradle 文件中.
compile('org.springframework.cloud:spring-cloud-starter-config')
现在,你需要将@RefreshScope注释添加到主Spring Boot应用程序中. @RefreshScope注释用于从Config服务器加载配置属性值.
package com.example.configclient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.context.config.annotation.RefreshScope; @SpringBootApplication @RefreshScope public class ConfigclientApplication { public static void main(String[] args) { SpringApplication.run(ConfigclientApplication.class, args); } }
现在,在application.properties文件中添加配置服务器URL并提供应用程序名称.
注意 : 在启动配置客户端应用程序之前,应该运行http://localhost:8888配置服务器.
spring.application.name = config-client spring.cloud.config.uri = http://localhost:8888
编写简单REST端点以读取欢迎消息的代码配置服务器在下面给出 :
package com.example.configclient; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RefreshScope @RestController public class ConfigclientApplication { @Value("${welcome.message}") String welcomeText; public static void main(String[] args) { SpringApplication.run(ConfigclientApplication.class, args); } @RequestMapping(value = "/") public String welcomeText() { return welcomeText; } }
您可以创建可执行的JAR文件,并使用以下Maven或Gradle命令运行Spring Boot应用程序 :
对于Maven,您可以使用下面显示的命令 :
mvn clean install
在"BUILD SUCCESS"之后,您可以在目标目录下找到JAR文件.
对于Gradle,您可以使用下面显示的命令 :
gradle clean build
之后"BUILD SUCCESSFUL",您可以在build/libs目录下找到JAR文件.
现在,使用此处显示的命令运行JAR文件:
java -jar <JARFILE>
现在,应用程序已在Tomcat端口8080上启动,如下所示 :
您可以在控制台窗口中看到日志; config-client应用程序从 https://localhost:8888
获取配置
2017-12-08 12:41:57.682 INFO 1104 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at: http://localhost:8888
现在点击URL,从配置服务器加载 http://localhost:8080/欢迎消息.
现在,转到配置服务器上的属性值并点击执行器端点POST URL http://localhost:8080/refresh 并在URL http://localhost:8080/
中查看新配置属性值
在本章中,我们将看到如何使用Maven和Gradle依赖项为Spring Boot应用程序创建Docker镜像.
创建Dockerfile
首先,在目录 src/main/docker 下创建一个名为 Dockerfile 的文件,其内容如下所示.请注意,此文件对于创建Docker镜像非常重要.
FROM java:8 VOLUME /tmp ADD dockerapp-0.0.1-SNAPSHOT.jar app.jar RUN bash -c 'touch /app.jar' ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
Maven
对于Maven,添加Docker Maven插件到你的构建配置文件中 pom.xml
<properties> <docker.image.prefix>spring-boot-it1352</docker.image.prefix> </properties> <build> <plugins> <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>1.0.0</version> <configuration> <imageName>${docker.image.prefix}/${project.artifactId}</imageName> <dockerDirectory>src/main/docker</dockerDirectory> <resources> <resource> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resource> </resources> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
完整的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>com.it1352</groupId> <artifactId>dockerapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>dockerapp</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <docker.image.prefix>spring-boot-it1352</docker.image.prefix> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>1.0.0</version> <configuration> <imageName>${docker.image.prefix}/${project.artifactId}</imageName> <dockerDirectory>src/main/docker</dockerDirectory> <resources> <resource> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resource> </resources> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
现在,您可以使用Maven命令运行您的应用程序 mvn package docker:build
注意 : 在没有TLS的情况下在 tcp://localhost:2375 上启用Expose守护程序.
在构建成功后,您可以在控制台上看到输出,如下所示 :
现在,请参阅Docker图像命令使用docker镜像并在控制台上查看图像信息.
Gradle
要使用Gradle构建配置构建Docker镜像,我们需要添加 docker 插件并需要编写任务 buildDocker 创建一个Docker镜像.
下面给出了Gradle Docker配置的代码.
buildscript { ..... dependencies { ..... classpath('se.transmode.gradle:gradle-docker:1.2') } } group = 'spring-boot-it1352' ..... apply plugin: 'docker' task buildDocker(type: Docker, dependsOn: build) { applicationName = jar.baseName dockerfile = file('src/main/docker/Dockerfile') doFirst { copy { from jar into stageDir } } }
完整的build.gradle文件如下所示.
buildscript { ext { springBootVersion = '1.5.9.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") classpath('se.transmode.gradle:gradle-docker:1.2') } } group = 'spring-boot-it1352' apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'docker' group = 'com.it1352' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') } task buildDocker(type: Docker, dependsOn: build) { applicationName = jar.baseName dockerfile = file('src/main/docker/Dockerfile') doFirst { copy { from jar into stageDir } } }
现在,使用下面显示的命令创建一个Docker镜像 :
gradle build buildDocker
执行命令后,您可以在控制台窗口中看到BUILD SUCCESSFUL日志.
现在,请查看Docker图像.命令使用 docker images 并在控制台上查看图像信息.
Hystrix是Netflix的一个库. Hystrix隔离了服务之间的访问点,阻止了它们之间的级联故障,并提供了后备选项.
例如,当您调用3 rd 方时应用程序,发送响应需要更多时间.那么在那个时候,控件转到了回退方法并将自定义响应返回给你的应用程序.
在本章中,您将看到如何在Spring Boot应用程序中实现Hystrix .
首先,我们需要在构建配置文件中添加Spring Cloud Starter Hystrix依赖项.
Maven用户可以添加以下依赖项pom.xml文件 :
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency>
Gradle用户可以在build.gradle文件中添加以下依赖项 :
compile('org.springframework.cloud:spring-cloud-starter-hystrix')
现在,将@EnableHystrix注释添加到主要内容中Spring Boot应用程序类文件. @EnableHystrix注释用于将Hystrix功能启用到Spring Boot应用程序中.
主要的Spring Boot应用程序类文件代码在下面和下面给出;
package com.it1352.hystrixapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.hystrix.EnableHystrix; @SpringBootApplication @EnableHystrix public class HystrixappApplication { public static void main(String[] args) { SpringApplication.run(HystrixappApplication.class, args); } }
现在编写一个简单的Rest Controller,使其在请求时间3秒后返回String.
@RequestMapping(value = "/") public String hello() throws InterruptedException { Thread.sleep(3000); return "Welcome Hystrix"; }
现在,为Rest API添加@Hystrix命令和@HystrixProperty,并以毫秒为单位定义超时值.
@HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") })
接下来,如果请求需要很长时间才能响应,请定义回退方法fallback_hello().
private String fallback_hello() { return "Request fails. It takes long time to response"; }
此处显示包含REST API和Hystrix属性的完整Rest Controller类文件 :
@RequestMapping(value = "/") @HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") }) public String hello() throws InterruptedException { Thread.sleep(3000); return "Welcome Hystrix"; } private String fallback_hello() { return "Request fails. It takes long time to response"; }
在此示例中,REST API编写在主Spring Boot应用程序类文件本身中.
package com.it1352.hystrixapp; import org.springframework.boot.SpringApplication; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; @SpringBootApplication @EnableHystrix @RestController public class HystrixappApplication { public static void main(String[] args) { SpringApplication.run(HystrixappApplication.class, args); } @RequestMapping(value = "/") @HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") }) public String hello() throws InterruptedException { Thread.sleep(3000); return "Welcome Hystrix"; } private String fallback_hello() { return "Request fails. It takes long time to response"; } }
完整的构建配置文件如下:
Maven - 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>com.it1352</groupId> <artifactId>hystrixapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>hystrixapp</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Gradle - build.gradle
buildscript { ext { springBootVersion = '1.5.9.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.it1352' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = 'Edgware.RELEASE' } dependencies { compile('org.springframework.cloud:spring-cloud-starter-hystrix') compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } }
您可以创建一个可执行的JAR文件,并使用以下Maven或Gradle命令运行Spring Boot应用程序 :
对于Maven,使用命令如图所示 :
mvn clean install
"BUILD SUCCESS"之后",你可以在目标目录下找到JAR文件.
对于Gradle,使用如下所示的命令 :
gradle clean build
在"BUILD SUCCESSFUL"之后,你可以在build/libs目录下找到JAR文件.
现在,使用下面给出的命令运行JAR文件 :
java -jar <JARFILE>
这将在Tomcat端口8080上启动应用程序,如下所示 :
现在,从网络浏览器点击URL http://localhost:8080/,并看到Hystrix的回应. API需要3秒钟才能响应,但Hystrix超时为1秒.
kafka:https://www.it1352.com/OnLineTutorial/spring_boot/spring_boot_apache_kafka.html