快速入门微服务框架 Spring Cloud,构建一个可用的基于 Spring Cloud 的微服务工程。
本 Chat 你将会获得以下在工作中常用 Spring Cloud 组件:
@TOC
服务名称 | 服务端口 | 服务说明 |
---|---|---|
hello-spring-cloud-config | 8888 | 分布式配置中心 |
hello-spring-cloud-eureka | 8000 | 服务注册与发现中心 |
hello-spring-cloud-provider | 8100 | 服务提供者 |
hello-spring-cloud-consumer | 8200 | 服务消费者,集成 Ribbon + Feign + Hystrix |
hello-spring-cloud-zuul | 8300 | 分布式服务路由网关 |
hello-spring-cloud-zipkin | 8400 | 分布式服务链路追踪 |
hello-spring-cloud-admin | 8500 | 分布式服务监控 |
介绍
Spring Cloud 项目都是基于 Spring Boot 进行开发,目前大部分公司都会使用 Maven 来构建管理项目,所以在实际开发中,一般都会创建一个 Maven 依赖管理项目作为 Parent 项目,这样的话可以很方便对项目中的 Jar 包版本进行统一管理。
在项目下创建目录 hello-spring-cloud-dependencies
4.0.0 org.springframework.boot spring-boot-starter-parent 2.0.3.RELEASE com.antoniopeng hello-spring-cloud-dependencies 1.0.0-SNAPSHOT pom 1.8 UTF-8 UTF-8 Finchley.RELEASE 2.10.1 2.0.1 org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import io.zipkin.java zipkin ${sprin-cloud-zipkin.version} io.zipkin.java zipkin-server ${sprin-cloud-zipkin.version} io.zipkin.java zipkin-autoconfigure-ui ${sprin-cloud-zipkin.version} de.codecentric spring-boot-admin-starter-server ${spring-cloud-admin.version} de.codecentric spring-boot-admin-starter-client ${spring-cloud-admin.version} org.apache.maven.plugins maven-compiler-plugin true org.apache.maven.plugins maven-jar-plugin false true true true org.apache.maven.plugins maven-resources-plugin org.apache.maven.plugins maven-install-plugin org.apache.maven.plugins maven-clean-plugin org.apache.maven.plugins maven-antrun-plugin org.apache.maven.plugins maven-dependency-plugin org.apache.maven.plugins maven-javadoc-plugin prepare-package jar net.alchim31.maven yuicompressor-maven-plugin 1.5.1 prepare-package compress UTF-8 false true 30000 true **/*.js **/*.css **/*.min.js **/*.min.css src/main/java **/*.java src/main/resources aliyun-repos Aliyun Repository http://maven.aliyun.com/nexus/content/groups/public true false sonatype-repos Sonatype Repository https://oss.sonatype.org/content/groups/public true false sonatype-repos-s Sonatype Repository https://oss.sonatype.org/content/repositories/snapshots false true spring-snapshots Spring Snapshots https://repo.spring.io/snapshot true spring-milestones Spring Milestones https://repo.spring.io/milestone false aliyun-repos Aliyun Repository http://maven.aliyun.com/nexus/content/groups/public true false
托管为 Maven 项目
Eureka 介绍
Eureka 是 Spring Cloud 的组件 Spring Cloud Netflix 中的一个模块,负责完成对微服务架构的服务注册与发现功能。
Eureka 服务的三个角色
服务注册发现:Eureka 提供的服务端,负责服务的注册与发现功能,一般称为 eureka server。
服务提供者:提供服务的应用,将自己提供的服务注册到 Eureka,以供其他应用发现
服务消费者:消费者应用从服务注册中心获取提供的服务列表, 从而使消费者可以知道去何处调用其所需要的服务
在项目下创建工程目录 hello-spring-cloud-eureka
服务结构预览创建 pom.xml,同样托管为 Maven 项目
4.0.0 com.antoniopeng hello-spring-cloud-dependencies 1.0.0-SNAPSHOT ../hello-spring-cloud-dependencies/pom.xml hello-spring-cloud-eureka jar org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-netflix-eureka-server org.springframework.boot spring-boot-maven-plugin com.antoniopeng.hello.spring.cloud.eureka.EurekaApplication
以上配置主要添加依赖 spring-cloud-starter-netflix-eureka-server
org.springframework.cloud spring-cloud-starter-netflix-eureka-server
创建 bootstrap.yml
spring: application: # 指定服务名,全局唯一 name: hello-spring-cloud-eurekaserver: # 服务端口 port: 8000eureka: instance: # 指定主机 hostname: localhost client: # 声明为 Eureka 服务端,默认为 Eureka 客户端 registerWithEureka: false fetchRegistry: false serviceUrl: # 指定 Eureka 服务端网址 defaultZone: http://localhost:8000/eureka/
主要添加配置
eureka: instance: # 指定主机 hostname: localhost client: # 声明为 Eureka 服务端,默认为 Eureka 客户端 registerWithEureka: false fetchRegistry: false serviceUrl: # 指定 Eureka 服务端网址 defaultZone: http://localhost:8000/eureka/
eureka.instance.hostname=localhost
: 指定 eureka 主机地址eureka.client.registerWithEureka=false
/ eureka.client.fetchRegistry=false
: 声明为 Eureka 服务端,默认为 Eureka 客户端eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/
:指定 eureka 服务端地址创建入口类 Application
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@EnableEurekaServer@SpringBootApplicationpublic class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); }}
主要添加注解
@EnableEurekaServer
:开启 Eureka 服务端启动服务并访问 Eureka 服务端,如图所示
所有向 Eureka 注册过的服务都会在该业面显示,可以看到目前并没有任何服务展示在该页面
在项目下创建工程目录 hello-spring-cloud-provider
创建 pom.xml,同样托管为 Maven
项目
4.0.0 com.antoniopeng hello-spring-cloud-dependencies 1.0.0-SNAPSHOT ../hello-spring-cloud-dependencies/pom.xml hello-spring-cloud-provider jar org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-netflix-eureka-server org.springframework.boot spring-boot-maven-plugin com.antoniopeng.hello.spring.cloud.provider.ProviderApplication
创建 bootstrap.yml
spring: application: # 服务名 name: hello-spring-cloud-providerserver: # 端口号 port: 8100eureka: client: serviceUrl: # 指定 Eureka 服务端 defaultZone: http://localhost:8000/eureka/
创建入口类 Application
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@EnableEurekaClient@SpringBootApplicationpublic class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); }}
主要添加注解
@EnableEurekaClient
:开启 Eureka 客户端创建 Controller 提供服务
import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class IndexController { @Value("${server.port}") private String port; @RequestMapping(value = "hi") public String sayHi(String message) { return "port : " + port + ",message : " + message; }}
启动服务提供者
在项目下创建工程目录 hello-spring-cloud-consumer
创建 pom.xml,同样托管为 Maven
项目
4.0.0 com.antoniopeng hello-spring-cloud-dependencies 1.0.0-SNAPSHOT ../hello-spring-cloud-dependencies/pom.xml hello-spring-cloud-consumer jar org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-test test net.sourceforge.nekohtml nekohtml org.springframework.cloud spring-cloud-starter-netflix-eureka-server org.springframework.cloud spring-cloud-starter-openfeign org.springframework.cloud spring-cloud-starter-netflix-hystrix org.springframework.cloud spring-cloud-starter-netflix-hystrix-dashboard org.springframework.boot spring-boot-maven-plugin com.antoniopeng.hello.spring.cloud.consumer.ConsumerApplication
主要添加依赖 spring-cloud-starter-openfeign
和 spring-cloud-starter-netflix-hystrix
和 spring-cloud-starter-netflix-hystrix-dashboard
org.springframework.cloud spring-cloud-starter-openfeign org.springframework.cloud spring-cloud-starter-netflix-hystrix org.springframework.cloud spring-cloud-starter-netflix-hystrix-dashboard
组件介绍
Ribbon
:实现服务的负载均衡调用Feign
:Feign
默认集成了 Ribbon
,并和 Eureka
结合,默认实现负载均衡的效果Hystrix
:由于网络原因或者自身的原因,当服务不可用时,Hystrix
熔断器将会被打开,为了避免连锁故障,可以创建 fallback
回调方法实现服务降级,即 fallback
方法返回一个值告知后面的请求该服务不可用了创建 bootstrap.yml
spring: application: # 指定服务名 name: hello-spring-cloud-consumer # thymeleaf 相关配置 thymeleaf: cache: false mode: LEGACYHTML5 encoding: UTF-8 servlet: content-type: text/htmlserver: port: 8200eureka: client: serviceUrl: defaultZone: http://localhost:8000/eureka/feign: hystrix: # 开启 Hystrix 功能 # Feign 中自带 Hystrix,默认是关闭的 enabled: true
eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/
:指定 eureka 服务端主要添加配置
feign: hystrix: # 开启 Hystrix 功能 # Feign 中自带 Hystrix,默认是关闭的 enabled: true
feign.hystrix.enabled=true
:开启 Hystrix 熔断器创建入口类 Application
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;import org.springframework.cloud.openfeign.EnableFeignClients;@EnableHystrixDashboard@EnableFeignClients@EnableDiscoveryClient@SpringBootApplicationpublic class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}
主要添加注解
@EnableDiscoveryClient
:开启扫描 Eureka
服务功能@EnableFeignClients
:开启 Feign
客户端@EnableHystrixDashboard
:开启 Hystrix
仪表盘功能创建服务消费接口 ProviderService
import com.antoniopeng.hello.spring.cloud.consumer.service.hystrix.ProviderServiceHystrix;import org.springframework.cloud.openfeign.FeignClient;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;@FeignClient(value = "hello-spring-cloud-provider")public interface ProviderService { @RequestMapping(value = "hi", method = RequestMethod.GET) String sayHi(@RequestParam("message") String message);}
@FeignClient(value = "hello-spring-cloud-provider)"
:声明调用的服务
创建服务熔断方法 ProviderServiceHystrix
如果服务调用失败,则会调用该方法实现服务降级
import com.antoniopeng.hello.spring.cloud.consumer.service.ProviderService;import org.springframework.stereotype.Component;@Componentpublic class ProviderServiceHystrix implements ProviderService { @Override public String sayHi(String message) { return "Hi,your message is :\"" + message + "\" but request error."; }}
在服务消费接口 ProviderService
中配置熔断方法,否则熔断方法不会生效
@FeignClient(value = "hello-spring-cloud-provider")
修改为 @FeignClient(value = "hello-spring-cloud-provider", fallback = ProviderServiceHystrix.class)
创建熔断器仪表盘配置 HystrixDashboardConfiguration
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class HystrixDashboardConfiguration { @Bean public ServletRegistrationBean getServlet() { HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet(); ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet); registrationBean.setLoadOnStartup(1); registrationBean.addUrlMappings("/hystrix.stream"); registrationBean.setName("HystrixMetricsStreamServlet"); return registrationBean; }}
创建 Controller 消费服务
import com.antoniopeng.hello.spring.cloud.consumer.service.ProviderService;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;@RestControllerpublic class ConsumerController { @Resource private ProviderService providerService; @RequestMapping(value = "hi", method = RequestMethod.GET) public String sayHi(@RequestParam String message) { return providerService.sayHi(message); }}
启动服务访问 http:localhost:8200/hi?message=hellospringcloud,如图所示,会发现调用了 spring-cloud-provider 服务
介绍
Zuul
的主要功能是路由转发和过滤器。路由功能是微服务的一部分,比如 /api/admin
转发到到 Admin
服务,/api/member
转发到 Member
服务。Zuul
默认和 Ribbon
结合实现了负载均衡的功能。
在项目下创建工程目录 hello-spring-cloud-zuul
创建 pom.xml,同样托管为 Maven
项目
4.0.0 com.antoniopeng hello-spring-cloud-dependencies 1.0.0-SNAPSHOT ../hello-spring-cloud-dependencies/pom.xml hello-spring-cloud-zuul jar org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-netflix-eureka-server org.springframework.cloud spring-cloud-starter-netflix-zuul org.springframework.boot spring-boot-maven-plugin com.antoniopeng.hello.spring.cloud.zuul.ZuulApplication
主要添加依赖 spring-cloud-starter-netflix-zuul
org.springframework.cloud spring-cloud-starter-netflix-zuul
创建 bootstrap.yml
spring: application: name: hello-spring-cloud-zuulserver: port: 8300eureka: client: serviceUrl: defaultZone: http://localhost:8000/eureka/zuul: routes: consumer: # 访问 /consumer 转发到 hello-spring-cloud-consumer 服务 path: /consumer/** serviceId: hello-spring-cloud-consumer
主要添加配置
zuul: routes: consumer: # 访问 /consumer 转发到 hello-spring-cloud-consumer 服务 path: /consumer/** serviceId: hello-spring-cloud-consumer
创建入口类 Application
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;import org.springframework.cloud.netflix.zuul.EnableZuulProxy;@EnableZuulProxy@EnableEurekaClient@SpringBootApplicationpublic class ZuulApplication { public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); }}
主要添加注解
@EnableZuulProxy
:开启 Zuul
路由代理功能启动服务访问 http://localhost:8300/consumer/hi?message=hellospringcloud,如图所示,会发现调用了 spring-cloud-consumer 服务
介绍
ZipKin
是一个开放源代码的分布式跟踪系统,用于收集服务的定时数据,以解决微服务架构中的延迟问题。包括数据的收集、存储、查找和展现。每个服务向 Zipkin
报告计时数据,Zipkin
会根据调用关系通过 Zipkin UI
生成依赖关系图,显示了多少跟踪请求通过每个服务。该组件可以让我们通过一个 Web
前端轻松的收集和分析数据。例如用户每次请求服务的处理时间等,可方便的监测系统中存在的瓶颈。
在项目下创建工程目录 hello-spring-cloud-zipkin
服务结构预览创建 pom.xml,同样托管为 Maven
项目
4.0.0 com.antoniopeng hello-spring-cloud-dependencies 1.0.0-SNAPSHOT ../hello-spring-cloud-dependencies/pom.xml hello-spring-cloud-zipkin jar org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-netflix-eureka-server org.springframework.cloud spring-cloud-starter-zipkin io.zipkin.java zipkin io.zipkin.java zipkin-server org.springframework.boot spring-boot-starter-log4j2 io.zipkin.java zipkin-autoconfigure-ui org.springframework.boot spring-boot-maven-plugin com.antoniopeng.itoken.zipkin.ZipKinApplication
主要添加依赖 spring-cloud-starter-zipkin
和 zipkin
和 zipkin-server
以及 zipkin-autoconfigure-ui
org.springframework.cloud spring-cloud-starter-zipkin io.zipkin.java zipkin io.zipkin.java zipkin-server org.springframework.boot spring-boot-starter-log4j2 io.zipkin.java zipkin-autoconfigure-ui
创建 bootstrap.yml
spring: application: name: hello-spring-cloud-zipkinserver: port: 8400eureka: client: serviceUrl: defaultZone: http://localhost:8000/eureka/# Zipkin 配置management: metrics: web: server: auto-time-requests: false
主要添加配置
management: metrics: web: server: auto-time-requests: false
创建入口类 Application
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;import zipkin.server.internal.EnableZipkinServer;@EnableZipkinServer@EnableEurekaClient@SpringBootApplicationpublic class ZipkinApplication { public static void main(String[] args) { SpringApplication.run(ZipkinApplication.class, args); }}
主要添加注解
@EnableZipkinServer
:开启 Zipkin 服务端配置 Zipkin 客户端
在所需要被追踪的服务中添加以下配置:
pom.xml
org.springframework.cloud spring-cloud-starter-zipkin
bootstrap.yml
spring: zipkin: base-url: http://localhost:8400
启动服务访问 http://localhost:8400,如图所示
介绍
随着开发周期的推移,项目会不断变大,切分出的服务也会越来越多,这时一个个的微服务构成了错综复杂的系统。对于各个微服务系统的健康状态、会话数量、并发数、服务资源、延迟等度量信息的收集就成为了一个挑战。 Spring Boot Admin
就是基于这些需求开发出的一套功能强大的监控管理系统。
在项目下创建工程目录 hello-spring-cloud-provider
服务结构预览创建 pom.xml,同样托管为 Maven
项目
4.0.0 com.antoniopeng hello-spring-cloud-dependencies 1.0.0-SNAPSHOT ../hello-spring-cloud-dependencies/pom.xml hello-spring-cloud-admin jar org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat org.springframework.boot spring-boot-starter-webflux org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-netflix-eureka-server org.jolokia jolokia-core de.codecentric spring-boot-admin-starter-server org.springframework.boot spring-boot-maven-plugin com.antoniopeng.spring.cloud.admin.AdminApplication
主要添加依赖
org.jolokia jolokia-core de.codecentric spring-boot-admin-starter-server
创建 bootstrap.yml
spring: application: name: hello-spring-cloud-adminserver: port: 8500eureka: client: serviceUrl: defaultZone: http://localhost:8000/eureka/# Admin 监控配置management: endpoint: health: show-details: always endpoints: web: exposure: include: health,info
主要添加配置
management: endpoint: health: show-details: always endpoints: web: exposure: include: health,info
创建入口类 Application
import de.codecentric.boot.admin.server.config.EnableAdminServer;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@EnableAdminServer@EnableEurekaClient@SpringBootApplicationpublic class AdminApplication { public static void main(String[] args) { SpringApplication.run(AdminApplication.class, args); }}
主要添加注解
@EnableAdminServer
:开启 Admin
服务端配置 Spring Boot Admin 客户端
在所需要被监控的服务中添加以下配置:
pom.xml
org.jolokia jolokia-core de.codecentric spring-boot-admin-starter-client
bootstrap.yml
spring: boot: admin: client: url: http://localhost:8500
启动服务访问 http://localhost:8500,如图所示
介绍
在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。Spring Cloud Config
,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程 Git
仓库中。
在项目下创建工程目录 hello-spring-cloud-config
创建 pom.xml,同样托管为 Maven
项目
4.0.0 com.antoniopeng hello-spring-cloud-dependencies 1.0.0-SNAPSHOT ../hello-spring-cloud-dependencies/pom.xml hello-spring-cloud-config jar org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-netflix-eureka-server org.springframework.cloud spring-cloud-config-server org.springframework.boot spring-boot-maven-plugin com.antoniopeng.hello.spring.cloud.config.ConfigApplication
主要添加依赖
org.springframework.cloud spring-cloud-config-server
创建 bootstrap.yml
spring: application: name: hello-spring-cloud-config cloud: config: label: master server: git: uri: {uri} search-paths: {search-paths} username: {username} password: {password}server: port: 8888eureka: client: serviceUrl: defaultZone: http://localhost:8000/eureka/
主要添加配置
spring: cloud: config: label: master server: git: uri: {uri} search-paths: {search-paths} username: {username} password: {password}
配置说明:
spring.cloud.config.label
:仓库访问分支spring.cloud.config.server.git.uri
:仓库地址spring.cloud.config.server.git.search-paths
:访问仓库中的路径(一般是文件夹)spring.cloud.config.server.git.username
:仓库访问账号spring.cloud.config.server.git.password
:仓库访问密码创建入口类 Application
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.config.server.EnableConfigServer;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@EnableConfigServer@EnableEurekaClient@SpringBootApplicationpublic class ConfigApplication { public static void main(String[] args) { SpringApplication.run(ConfigApplication.class, args); }}
主要添加注解
@EnableConfigServer
:开启 Config 配置中心服务端配置 Config 客户端
在所需要配置的服务中添加以下配置,这里以改造 hello-srping-cloud-eureka
服务为例,其它服务同理。
新建 hello-spring-cloud-eureka-dev.yml
,并将 hello-srping-cloud-eureka
服务中的 bootstrap.yml
里的配置信息剪切到该文件中
将 hello-spring-cloud-eureka-dev.yml
上传到你的 Git
仓库z
修改 hello-srping-cloud-eureka
服务中的 bootstrap.yml
spring: cloud: config: uri: http://localhost:8888 name: hello-spring-cloud-eureka label: master profile: dev
先后启动服务 hello-srping-cloud-config
和 hello-srping-cloud-eureka
访问 Eureka 服务端
注:如果配置文件从 Config 分布式配置中心获取时,需要先启动 Config 服务端 hello-spring-cloud-config
,否则会访问不到配置文件
项目已上传至 GitHub
阅读全文: http://gitbook.cn/gitchat/activity/5d8daeb3531d0d6a1d45279a
您还可以下载 CSDN 旗下精品原创内容社区 GitChat App ,阅读更多 GitChat 专享技术内容哦。