边作边学,基于Spring Cloud的微服务架构最佳实践

本文节选自开源无服务器PaaS Rainbond文档,原文请戳连接html

概述

微服务是能够独立部署、水平扩展、独立访问(或者有独立的数据库)的服务单元,Spring Cloud则是用来管理微服务的一系列框架的有序集合。利用Spring Boot的开发便利性,Spring Cloud巧妙简化了分布式系统基础设施的开发,例如服务发现注册、配置中心、消息总线、负载均衡、断路器等,均可以用Spring Boot的开发风格作到一键启动和部署。git

Spring Cloud并无重复造轮子,而是将目前各家公司开发的比较成熟、经得起实际考验的服务框架组合起来,经过Spring Boot风格进行再封装,屏蔽掉了复杂的配置和实现原理,最终为开发者提供了一套简单易懂、易部署、易维护的分布式系统开发工具包。github

Spring Cloud有不少组件,其中最核心的组件有:Eureka(注册中心)、Hystrix(断路器)、Config(配置中心)、Zuul(代理、网关)等等。web

接下来,咱们不妨经过几个demo来了解Spring Cloud是如何一步步构建起来的。spring

示例源码请戳源码数据库

  • 如何搭建Eureka
  • 如何搭建Hystrix
  • 如何搭建Config
  • 如何搭建Zuul

如何搭建Eureka

组件介绍

注册中心Eureka是一个基于REST的服务,用于各个服务之间的互相发现。任何服务须要其它服务的支持都须要经过它获取;一样的,全部的服务都须要来这里注册,方便之后其它服务来调用。Eureka的好处是你不须要知道找什么服务,只须要到注册中心来获取,也不须要知道提供支持的服务在哪里、是几个服务来支持的,直接来这里获取就能够了。如此一来,便提高了稳定性,也下降了微服务架构搭建的难度。bootstrap

项目描述

正常调用服务A请求服务B:后端

<div align=center>
<img src="http://grstatic.oss-cn-shangh...; width="50%" height="50%">
</div>浏览器

有了服务中心以后,服务A不能直接调用服务B,而是A,B经过在注册中心中注册服务,而后互相发现,服务A经过注册中心来调用服务B:springboot

<div align=center>
<img src="http://grstatic.oss-cn-shangh...; width="75%" height="75%">
</div>

以上只是2个服务之间的相互调用,若是有十几个甚至几十个服务,其中任何的一个项目改动,就可能牵连到好几个项目的重启,很麻烦并且容易出错。经过注册中心来获取服务,你不须要关注你调用的项目IP地址,由几台服务器组成,每次直接去注册中心获取可使用的服务去调用既可。

部署到云帮

注册服务

一、pom中添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter</artifactId>
    </dependency>
    <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>

二、添加启动代码中添加@EnableEurekaServer注解

@SpringBootApplication
@EnableEurekaServer
public class SpringCloudEurekaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCloudEurekaApplication.class, args);
    }
}

三、配置文件

在默认设置下,该服务注册中心也会将本身做为客户端来尝试注册它本身,因此咱们须要禁用它的客户端注册行为,在application.properties添加如下配置:

spring.application.name=spring-cloud-eureka

server.port=8000
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
  • eureka.client.register-with-eureka :表示是否将本身注册到Eureka Server,默认为true。
  • eureka.client.fetch-registry :表示是否从Eureka Server获取注册信息,默认为true。
  • eureka.client.serviceUrl.defaultZone :设置与Eureka Server交互的地址,查询服务和注册服务都须要依赖这个地址。默认是http://localhost:8761/eureka ;多个地址可以使用 , 分隔。

启动工程后,访问:http://localhost:8000/,能够看到下面的页面,其中尚未发现任何服务

<div align=center>
<img src="http://grstatic.oss-cn-shangh...; width="100%" height="100%">
</div>

服务提供者(B)

一、pom包配置

建立一个springboot项目,pom.xml中添加以下配置:

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

二、配置文件

application.properties配置以下:

spring.application.name=spring-cloud-producer
server.port=9000
eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/

三、启动类

启动类中添加@EnableDiscoveryClient注解

@SpringBootApplication
@EnableDiscoveryClient
public class ProducerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProducerApplication.class, args);
    }
}

四、服务提供

提供hello服务:

@RestController
public class HelloController {
    
    @RequestMapping("/hello")
    public String index(@RequestParam String name) {
        return "hello "+name+",this is first messge";
    }
}

添加@EnableDiscoveryClient注解后,项目就具备了服务注册的功能。启动工程后,就能够在注册中心的页面看到SPRING-CLOUD-PRODUCER服务。

<div align=center>
<img src="http://grstatic.oss-cn-shangh...; width="100%" height="100%">
</div>

到此服务提供者配置就完成了。

服务消费者(A)

一、pom包配置

和服务提供者一致

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

二、配置文件

application.properties配置以下:

spring.application.name=spring-cloud-consumer
server.port=9001
eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/

三、启动类

启动类添加@EnableDiscoveryClient@EnableFeignClients注解:

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

}
  • @EnableDiscoveryClient :启用服务注册与发现
  • @EnableFeignClients:启用feign进行远程调用

Feign是一个声明式Web Service客户端。使用Feign能让编写Web Service客户端更加简单, 它的使用方法是定义一个接口,而后在上面添加注解,同时也支持JAX-RS标准的注解。Feign也支持可拔插式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign能够与Eureka和Ribbon组合使用以支持负载均衡。

四、feign调用实现

@FeignClient(name= "spring-cloud-producer")
public interface HelloRemote {
    @RequestMapping(value = "/hello")
    public String hello(@RequestParam(value = "name") String name);
}
  • name:远程服务名,及spring.application.name配置的名称

此类中的方法和远程服务中contoller中的方法名和参数需保持一致。

五、web层调用远程服务

将HelloRemote注入到controller层,像普通方法同样去调用便可。

@RestController
public class ConsumerController {

    @Autowired
    HelloRemote HelloRemote;
    
    @RequestMapping("/hello/{name}")
    public String index(@PathVariable("name") String name) {
        return HelloRemote.hello(name);
    }

}

到此,最简单的一个服务注册与调用的例子就完成了。

测试

依次启动spring-cloud-eureka、spring-cloud-producer、spring-cloud-consumer三个项目。

先输入:http://localhost:9000/hello?name=neo 检查spring-cloud-producer服务是否正常

返回:hello neo,this is first messge

说明spring-cloud-producer正常启动,提供的服务也正常。

浏览器中输入:http://localhost:9001/hello/neo

返回:hello neo,this is first messge

说明客户端已经成功的经过feign调用了远程服务hello,而且将结果返回到了浏览器。

{{site.data.alerts.callout_danger}}
部署在云帮,须要验证必须保证一下3点:

  1. 端口开启了外部访问功能
  2. consumer关联了producer
  3. hello?name=neohello/neo添加在访问所产生的url后

以后组件的验证同理。

如何搭建Hystrix

组件介绍

​在微服务架构中一般会有多个服务层调用,基础服务的故障可能会致使级联故障,进而形成整个系统不可用的状况,这种现象被称为服务雪崩效应。而使用Hystrix(熔断器)就能够避免这种问题。

​熔断器的原理很简单,如同电力过载保护器。它能够实现快速失败,若是它在一段时间内侦测到许多相似的错误,会强迫其之后的多个调用快速失败,再也不访问远程服务器,从而防止应用程序不断地尝试执行可能会失败的操做,使得应用程序继续执行而不用等待修正错误,或者浪费CPU时间去等到长时间的超时产生。熔断器也可使应用程序可以诊断错误是否已经修正,若是已经修正,应用程序会再次尝试调用操做。

​当Hystrix Command请求后端服务失败数量超过必定比例(默认50%), 断路器会切换到开路状态(Open). 这时全部请求会直接失败而不会发送到后端服务. 断路器保持在开路状态一段时间后(默认5秒), 自动切换到半开路状态(HALF-OPEN). 这时会判断下一次请求的返回状况, 若是请求成功, 断路器切回闭路状态(CLOSED), 不然从新切换到开路状态(OPEN). Hystrix的断路器就像咱们家庭电路中的保险丝, 一旦后端服务不可用, 断路器会直接切断请求链, 避免发送大量无效请求影响系统吞吐量, 而且断路器有自我检测并恢复的能力。

<div align=center>
<img src="http://grstatic.oss-cn-shangh...; width="50%" height="50%">
</div>

项目描述

​经过将Hystrix组件添加到服务消费者,实现熔断效果,只须要在Eureka的demo基础加入Hystrix便可。

<div align=center>
<img src="http://grstatic.oss-cn-shangh...; width="50%" height="50%">
</div>

Hystrix是做用在服务调用端的,所以须要添加在A上。

部署到Rainbond

Hystrix服务

由于熔断只是做用在服务调用这一端,所以咱们根据上一篇的示例代码只须要改动消费者(A)服务相关代码就能够。由于,Feign中已经依赖了Hystrix因此在maven配置上不用作任何改动。

一、配置文件
application.properties添加这一条:

feign.hystrix.enabled=true

二、建立回调类

建立HelloRemoteHystrix类继承与HelloRemote实现回调的方法:

@Component
public class HelloRemoteHystrix implements HelloRemote{

    @Override
    public String hello(@RequestParam(value = "name") String name) {
        return "hello" +name+", this messge send failed ";
    }
}

三、添加fallback属性

HelloRemote类添加指定fallback类,在服务熔断的时候返回fallback类中的内容:

@FeignClient(name= "spring-cloud-producer",fallback = HelloRemoteHystrix.class)
public interface HelloRemote {

    @RequestMapping(value = "/hello")
    public String hello(@RequestParam(value = "name") String name);

}

四、测试

那咱们就来测试一下看看效果吧。

依次启动spring-cloud-eureka、spring-cloud-producer、spring-cloud-consumer三个项目。

浏览器中输入:http://localhost:9001/hello/neo

返回:hello neo,this is first messge

说明加入熔断相关信息后,不影响正常的访问。接下来咱们手动中止spring-cloud-producer项目再次测试:

浏览器中输入:http://localhost:9001/hello/neo

返回:hello neo, this messge send failed

根据返回结果说明熔断成功。

如何搭建Config

组件介绍

​ 随着线上项目变的日益庞大,每一个项目都散落着各类配置文件,若是采用分布式的开发模式,须要的配置文件随着服务增长而不断增多。某一个基础服务信息变动,都会引发一系列的更新和重启,不便于项目的维护,而Spring Cloud Config就是解决这个问题的。

业务描述

​目前Config支持git和svn做为存放配置文件的仓库,本次示例使用git仓库来存放配置文件。这里的Config-client 就至关于服务A和服务B,他们的配置文件都集中存放,经过Config-server来获取各自的配置文件。

<div align=center>
<img src="http://grstatic.oss-cn-shangh...; width="50%" height="50%">
</div>

部署到Rainbond

git仓库

首先在github上面建立了一个文件夹config-repo用来存放配置文件,为了模拟生产环境,咱们建立如下三个配置文件:

// 开发环境
neo-config-dev.properties
// 测试环境
neo-config-test.properties
// 生产环境
neo-config-pro.properties

每一个配置文件中都写一个属性neo.hello,属性值分别是 hello im dev/test/pro 。下面咱们开始配置server端

config-server端

一、添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>
</dependencies>

只须要加入spring-cloud-config-server包引用既可。

二、配置文件

server:
  port: 8040
spring:
  application:
    name: spring-cloud-config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/xxx                             # 配置git仓库的地址
          search-paths: config-repo                             # git仓库地址下的相对地址,能够配置多个,用,分割。
          username:                                             # git仓库的帐号
          password:                                             # git仓库的密码

Spring Cloud Config也提供本地存储配置的方式。咱们只须要设置属性spring.profiles.active=native,Config Server会默认从应用的src/main/resource目录下检索配置文件。也能够经过spring.cloud.config.server.native.searchLocations=file:E:/properties/属性来指定配置文件的位置。虽然Spring Cloud Config提供了这样的功能,可是为了支持更好的管理内容和版本控制的功能,仍是推荐使用git的方式。

三、启动类

启动类添加@EnableConfigServer,激活对配置中心的支持

@EnableConfigServer
@SpringBootApplication
public class ConfigServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

到此server端相关配置已经完成

四、测试server端

首先咱们先要测试server端是否能够读取到github上面的配置信息,直接访问:http://localhost:8001/neo-config/dev

返回信息以下:

{
    "name": "neo-config", 
    "profiles": [
        "dev"
    ], 
    "label": null, 
    "version": null, 
    "state": null, 
    "propertySources": [
        {
            "name": "https://github.com/goodrain-apps/spring-cloud-demo/config-repo/neo-config-dev.properties", 
            "source": {
                "neo.hello": "hello im dev update"
            }
        }
    ]
}

上述的返回的信息包含了配置文件的位置、版本、配置文件的名称以及配置文件中的具体内容,说明server端已经成功获取了git仓库的配置信息。

若是直接查看配置文件中的配置信息可访问:http://localhost:8001/neo-config-dev.properties,返回:neo.hello: hello im dev

修改配置文件neo-config-dev.properties中配置信息为:neo.hello=hello im dev update,再次在浏览器访问http://localhost:8001/neo-config-dev.properties,返回:neo.hello: hello im dev update。说明server端会自动读取最新提交的内容

仓库中的配置文件会被转换成web接口,访问能够参照如下的规则:

  • /{application}/{profile}[/{label}]
  • /{application}-{profile}.yml
  • /{label}/{application}-{profile}.yml
  • /{application}-{profile}.properties
  • /{label}/{application}-{profile}.properties

以neo-config-dev.properties为例子,它的application是neo-config,profile是dev。client会根据填写的参数来选择读取对应的配置。

Config-client端

主要展现如何在业务项目中去获取server端的配置信息

一、添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</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>

引入spring-boot-starter-web包方便web测试

二、配置文件

须要配置两个配置文件,application.properties和bootstrap.properties

application.properties以下:

spring.application.name=spring-cloud-config-client
server.port=8002

bootstrap.properties以下:

spring.cloud.config.name=neo-config
spring.cloud.config.profile=dev
spring.cloud.config.uri=http://localhost:8001/
spring.cloud.config.label=master
  • spring.application.name:对应{application}部分
  • spring.cloud.config.profile:对应{profile}部分
  • spring.cloud.config.label:对应git的分支。若是配置中心使用的是本地存储,则该参数无用
  • spring.cloud.config.uri:配置中心的具体地址
  • spring.cloud.config.discovery.service-id:指定配置中心的service-id,便于扩展为高可用配置集群。

上面这些与spring-cloud相关的属性必须配置在bootstrap.properties中,config部份内容才能被正确加载。由于config的相关配置会先于application.properties,而bootstrap.properties的加载也是先于application.properties。

三、启动类

启动类添加@EnableConfigServer,激活对配置中心的支持

@SpringBootApplication
public class ConfigClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigClientApplication.class, args);
    }
}

启动类只须要@SpringBootApplication注解就能够

四、web测试

使用@Value注解来获取server端参数的值

@RestController
class HelloController {
    @Value("${neo.hello}")
    private String hello;

    @RequestMapping("/hello")
    public String from() {
        return this.hello;
    }
}

启动项目后访问:http://localhost:8002/hello,返回:hello im dev update说明已经正确的从server端获取到了参数。到此一个完整的服务端提供配置服务,客户端获取配置参数的例子就完成了。

如何搭建Zuul

组件介绍

​在微服务架构中,后端服务每每不直接开放给调用端,而是经过一个API网关根据请求的url,路由到相应的服务。当添加API网关后,在第三方调用端和服务提供方之间就建立了一面墙,这面墙直接与调用方通讯进行权限控制,后将请求均衡分发给后台服务端。而用来进行代理调度的组件就是Zuul。

项目描述

​在项目中,只有Zuul提供对外访问,Gateway经过请求的url的不一样,将请求调度到不一样的后端服务

<div align=center>
<img src="http://grstatic.oss-cn-shangh...; width="75%" height="75%">
</div>

部署到Rainbond

Gateway

一、添加依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>

引入spring-cloud-starter-zuul

二、配置文件

spring.application.name=gateway-service-zuul
server.port=8888

#这里的配置表示,访问/producer/** 直接重定向到http://域名/**
zuul.routes.baidu.path=/producer/**
zuul.routes.baidu.url=http://域名/

三、启动类

@SpringBootApplication
@EnableZuulProxy
public class GatewayServiceZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayServiceZuulApplication.class, args);
    }
}

启动类添加@EnableZuulProxy,支持网关路由。

四、测试

启动gateway-service-zuul-simple项目,先输入:http://localhost:8888/producer/hello?name=neo

返回:hello neo,this is first messge

说明调度成功。

小结

至此,咱们就完成了Eureka、Hystrix、Config、Zuul等几个Spring Cloud最核心组件的搭建,更多内容敬请关注Rainbond文档

或参考云框架项目,[[云框架]基于Spring Cloud的微服务架构](https://github.com/cloudframe...

相关文章
相关标签/搜索