sb2.0新版springcloud微服务实战:Consul+Zuul+Feign/Ribbon+Hystrix Turbine+Config+sleuth+zipkin

sb2.0新版springcloud微服务实战:Eureka+Zuul+Feign/Ribbon+Hystrix Turbine+SpringConfig+sleuth+zipkin

springboot 版本是 2.0.3.RELEASE ,springcloud 版本是 Finchley.RELEASE

本篇文章是springboot2.x升级后的升级springcloud专贴,因为之前版本更新已经好久了,好多人评论可不可以出个新版本,大家一定要注意,这是springboot2.x版本的,springboot1.x的请参考 点击查看文章,基本组件都不变就是升级jar包版本,主要就是hystrix-dashboard使用有点变化。

相信现在已经有很多小伙伴已经或者准备使用springcloud微服务了,接下来为大家搭建一个微服务框架,后期可以自己进行扩展。会提供一个小案例: 服务提供者和服务消费者 ,消费者会调用提供者的服务,新建的项目都是用springboot,附源码下载,推荐使用coding地址下载,因为可以切换分支,后期可以及时更新。

coding仓库地址(推荐下载): coding地址 远程配置仓库地址 远程配置仓库地址

如果有问题请在下边评论,或者200909980加群交流。或者关注文章结尾微信公众号,私信后台

Eureka/Consul/Zookeeper:服务发现 (根据情况选择一个,eureka已经宣布闭源)
Hystrix:断路器
Zuul:智能路由
Ribbon/Feign:客户端负载均衡 (Feign用的更多)
Turbine&hystrix-dashboard:集群监控
Springcloud-config:远程获取配置文件

接下来,我们开始搭建项目,首先我们到spring为我们提供的一个网站快速搭建springboot项目,点击访问,我这里用的是gradle,如果各位客官喜欢用maven,好吧你可以到http://mvnrepository.com/查看对应的依赖,点我访问

微信截图_20180811140827.png

一、搭建consul服务

使用 eureka 作为服务发现 请参考点击查看使用eureka作为服务注册中心

springclound-consul作为服务发现的核心,第一个搭建,后面的服务都要注册到consul上,意思是告诉consul自己的服务地址是啥。当然还可以用zookeeper或者eureka。

  • 1下载安装consul
    consul的下载地址consul下载地址,根据自己电脑系统下载对应的包。
    我这里是windows64,网上说要配置环境变量,就可以直接使用,但是我这里不行。具体方法是,下载解压后是一个.exe可执行文件,然后配置当前路劲到path中,然后直接在cmd命令窗口中,输入consul agent -dev 就可以启动了,如果不行的话,就在cmd命令窗口进如到consul的下载目录,然后执行上面的命令。然后consul的默认端口是8500,直接在浏览器打开http://localhost:8500,就可以看到控制台了
    2.png

二、搭建config-server服务sc-config-server

springcloud-config-server是用来将远程git仓库的配置文件动态拉下来,这样配置文件就可以动态的维护了。当然也可以选择本地仓库。

新建一个springboot项目,修改maven私服地址,并加入一下依赖。

  • 1.修改build.gradle文件
compile('org.springframework.cloud:spring-cloud-config-server')
compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')
//连接config-server也需要用户名和密码
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-actuator')
  • 2.修改application.yml文件
server:
  port: 8800
spring:
  security:
    basic:
      enabled: true
    user:
      name: root
      password: booszy
  application:
    name: sc-config-server
  cloud:
    config:
      server:
        git:
          uri: https://git.coding.net/yirenyishi/springcloud-config-profile
          searchPaths: '{application}'
    consul:
      host: localhost
      port: 8500
      discovery:
        instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
        ip-address: true
  • 3.修改启动类

修改启动类,要加入这三个注解,因为要注册到consul上,所以需要@EnableDiscoveryClient这个注解

@EnableConfigServer
@EnableDiscoveryClient
@SpringBootApplication
public class Sb2scConfigApplication {
    public static void main(String[] args) {
        SpringApplication.run(Sb2scConfigApplication.class, args);
    }
}

然后运行启动springboot项目,等启动成功后访问consul的页面,会发现sc-config-server已经注册到上面了,如果启动报错,请检查错误信息。


3.png

三、搭建服务提供者服务sc-provider

编写一个服务提供者,为下边的消费者提供服务,用到了spring-webflux(spring新出的非阻塞式框架)不是springmvc,当然你们公司用什么你还是继续用什么。

  • 注意 : 这里除了application.xml,还需要一个bootstrap.yml, 因为bootstrap.yml得加载顺序是在application.xml前边,服务注册和config配置必须放到bootstrap.yml。
    1. 修改build.gradle文件
compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')
compile('org.springframework.cloud:spring-cloud-starter-config')
compile('org.springframework.boot:spring-boot-starter-webflux')
compile('org.springframework.boot:spring-boot-starter-actuator')
  • 2.编写配置文件bootstrap.yml

** 注意 : 这里除了application.xml,还需要一个bootstrap.yml*

application.xml我是放到远程仓库地址的,大家可以直接到我的远程仓库,根据项目名(sc-provider-config)查询。配置文件的仓库地址:点击访问

spring:
  application:
    name: sc-provider
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
      instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
      ip-address: true
    config:
      discovery:
        enabled: true
        service-id: sc-config-server
      fail-fast: true
      username: root
      password: booszy
      profile: csdn
  • 3.编写代码

编写主类

@EnableDiscoveryClient
@SpringBootApplication
public class Sb2scProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(Sb2scProviderApplication.class, args);
    }
}

新建IndexController进行测试,这里只是为了测试,案例代码使用的是webflux,如果想使用springmvc,修改jar包依赖即可。

@RestController
@RequestMapping("test")
public class IndexController {
    //返回一个实体
    @GetMapping("{msg}")
    public Mono<String> sayHelloWorld(@PathVariable("msg") String msg) {
        System.out.println("come on " + msg);
        return Mono.just("sc-provider receive : " +msg);
    }
    //返回一个列表
    @GetMapping("list")
    public Flux<Integer> list() {
        List<Integer> list = new ArrayList<>();
        list.add(8);
        list.add(22);
        list.add(75);
        list.add(93);
        Flux<Integer> userFlux = Flux.fromIterable(list);
        return userFlux;
    }
}

运行springboot项目,去consul查看,有没有注册上。


4.png

我们的sc-provider已经注册到eureka上了,访问接口,成功。


6.png

四、搭建消费者服务sc-consumer

消费者要访问服务提供者的服务,这里用的是通过RestTemplate/feign请求resetful接口,使用ribbon做客户端负载均衡,hystrix做错误处理,feign和ribbon二选一,案例中ribbon和feign都有,也可以都用。
还是熟悉的配方,熟悉的味道,新建springboot项目,添加项目依赖。

  • 1.修改build.gradle文件
compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')
compile('org.springframework.cloud:spring-cloud-starter-config')
compile('org.springframework.boot:spring-boot-starter-webflux')
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.cloud:spring-cloud-starter-openfeign')
compile('org.springframework.cloud:spring-cloud-starter-netflix-hystrix')
  • 2.修改bootstrap.yml文件

application.yml 在git仓库,请前往git仓库查看。

spring:
  application:
    name: sc-consumer
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
      instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
      ip-address: true
    config:
      discovery:
        enabled: true
        service-id: sc-config-server
      fail-fast: true
      username: root
      password: booszy
      profile: csdn
#新版配置,否则后面dashboard无法找到hystrix.stream
management:
  endpoints:
    web:
      exposure:
        include: '*'
  • 3.编写代码

启动类代码

@RibbonClient 指定服务使用的负载均衡类型,name不指定服务则为所有的服务打开负载均衡,也可以在用yml中进行配置。
@EnableHystrix 是支持hystrix打开断路器,在规定时间内失败参数超过一定参数,就会打开断路器,不会发起请求,而是直接进入到错误处理方法。

@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrix
@SpringBootApplication
public class Sb2scConsumerApplication {
    // ribbon需要配置,负载均衡
    @Autowired
    private RestTemplateBuilder builder;

    // ribbon需要配置,负载均衡
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return builder.build();
    }
    public static void main(String[] args) {
        SpringApplication.run(Sb2scConsumerApplication.class, args);
    }
}

1.ribbon案例

ribbon不需要单独依赖,新建 RibbonController
ribbon一个坑,不能接受List类型,要使用数组接收。
@HystrixCommand(fallbackMethod="fallbackMethod")
如果请求失败,会进入fallbackMethod这个方法,fallbackMethod这个方法要求参数和返回值与回调他的方法保持一致。

@RestController
public class RibbonController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/ribbon/{wd}")
    @HystrixCommand(fallbackMethod="fallbackMethod")
    public Mono<String> sayHelloWorld(@PathVariable("wd") String parm) {
        String res = this.restTemplate.getForObject("http://sc-provider/test/" + parm, String.class);
        return Mono.just(res);
    }

    public Mono<String> fallbackMethod(@PathVariable("wd") String parm) {
        return Mono.just("fallback");
    }

运行springboot项目,先看有没有注册到consul上。


5.png

注册成功后,访问接口,测试是否正确。

8.png

ribbon使用就是这么简单,ribbon是springboot自带,所以不需要单独添加依赖。

2.feign案例

在实际开发中,feign使用的还是挺多的,feign底层还是使用了ribbon。废话不多说,直接上步骤,在服务消费者中使用feign访问服务提供者。

  • 1配置文件
ribbon:
  ReadTimeout:  30000
  ConnectTimeout:  15000
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 10000

feign的默认请求超时时间是1s,所以经常会出现超时的问题,这里我设置的是10s。ribbon的请求时间也要设置,因为feign用的是ribbon。这里贴的是application.yml文件中的一小段

  • 2 编码

1、主类注解

@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrix

这三个都要,hystrix主要作用是断路器,会进如fein的fallback中。 主类代码在上面已经贴出来了

2、编写feign接口,MFeignClient.class

name是指要请求的服务名称。这里请求的是服务提供者
fallback 是指请求失败,进入断路器的类,和使用ribbon是一样的。
configuration 是feign的一些配置,例如编码器等。

@FeignClient(name = "sc-provider",fallback = MFeignClientFallback.class, configuration = MFeignConfig.class)
public interface MFeignClient {
    // 这是被请求微服务的地址,也就是provider的地址
    @GetMapping(value = "/test/{msg}")
    String sayHelloWorld(@PathVariable("msg") String msg);

    @GetMapping(value = "/test/list")
    List<Integer> list();

    @GetMapping(value = "/test/list")
    Integer[] array();
}
  • 3 MFeignConfig.class feign的配置

这里配置了feign的打印日志等级

@Configuration
public class MFeignConfig {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}
  • 4 MFeignClientFallback.class ,断路器回调方法

断路器要实现上边定义的MFeignClient接口,请求失败,进入断路器时,会回调这里的方法。

@Component
public class MFeignClientFallback implements MFeignClient{
    @Override
    public String sayHelloWorld(String msg) {
        return "fallback";
    }

    @Override
    public List<Integer> list() {
        return new ArrayList<>();
    }

    @Override
    public Integer[] array() {
        return new Integer[0];
    }
}
  • 5 在controller中使用feign
@RestController
public class FeignController {

    @Autowired
    private MFeignClient feignClient;

    @GetMapping("/feign/{wd}")
    public Mono<String> sayHelloWorld(@PathVariable("wd") String parm) {
        String result = feignClient.sayHelloWorld(parm);
        return Mono.just(result);
    }

    @GetMapping("/feign/list")
    public Flux<Integer> list() {
        List<Integer> list = feignClient.list();
        Flux<Integer> userFlux = Flux.fromIterable(list);
        return userFlux;
    }

    @GetMapping("/feign/array")
    public Flux<Integer> array() {
        Integer[] arrays = feignClient.array();
        Flux<Integer> userFlux = Flux.fromArray(arrays);
        return userFlux;
    }
}
9.png

五、用zuul做路由转发和负载均衡

这些微服务都是隐藏在后端的,用户是看不到,或者不是直接接触,可以用nginx或者zuul进行路由转发和负载均衡,zuul负载均衡默认用的是ribbon。

  • 1.修改build.gradle文件
compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')
compile('org.springframework.cloud:spring-cloud-starter-config')
compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul')
compile('org.springframework.boot:spring-boot-starter-actuator')
  • 2.修改bootstrap.yml

还是原来的配方,application.yml在git仓库

spring:
  application:
    name: sc-zuul
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
      instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
      ip-address: true
    config:
      discovery:
        enabled: true
        service-id: sc-config-server
      fail-fast: true
      username: root
      password: booszy
      profile: csdn
  • 3.启动类

@RefreshScope这个注解是当application.yml配置文件发生变化的时候,不需要手动的进行重启,调用localhost:8400/refresh,就会加载新的配置文件,当然正在访问的客户并不影响还是使用旧的配置文件,因为不是重启,后来的用户会使用新的配置文件。注意这块的刷新要用post请求

@EnableDiscoveryClient
@SpringBootApplication
@EnableZuulProxy
@RefreshScope
public class Sb2scZuulApplication {
    public static void main(String[] args) {
        SpringApplication.run(Sb2scZuulApplication.class, args);
    }
}

启动springboot项目,访问consul


6.png

这时候,我们就要通过zuul访问微服务了,而不是直接去访问微服务。
应该访问地址http://localhost:8400/sc-consumer/feign/list,这块你要换成你的zuul地址。

但是有些人就会说,这样以后用户请求会不会太长,比较反感,所以可以通过配置进行修改访问地址。

zuul:
  routes:
    springcloud-consumer-config: /consumer/**
    springcloud-provider-config: /provider/**

在application.yml中加入这样一段配置,其实就是nginx中的反向代理,使用一下简短的可以代理这个微服务。这个时候我们就可以这样去访问了http://localhost:8400/consumer/feign/list,是不是简短了很多

11.png

六、用hystrix-turbine-dashboard 做集群监控

项目在生产环境中,每个服务的访问量都不通,有些服务的访问量比较大,有时候有些服务挂了,不能继续服务,需要重启的时候,我们并不知道,所以这时候就需要使用hystrix-turbine-dashboard做一个监控,监控所有的微服务,可以看到这个接口实时访问量,和健康状况。
新建一个springboot项目,老套路,加入如下依赖

  • 1 添加依赖
compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.cloud:spring-cloud-starter-netflix-hystrix')
compile('org.springframework.cloud:spring-cloud-starter-netflix-hystrix-dashboard')
compile('org.springframework.cloud:spring-cloud-starter-netflix-turbine')

如果启动的时候报错要排除一下eureka依赖

configurations {
    compile.exclude module: 'eureka-client'
}
  • 2 修改application.yml配置文件
    注意:是application.yml,这里不需要bootstrap.yml
server:
  port: 8900
turbine:
  aggregator:
    clusterConfig: default
  appConfig: sc-consumer
  clusterNameExpression: "'default'"
spring:
  application:
    name: sc-dashboard
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
      instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
      ip-address: true

appConfig 后面是要检测的注册在consul上的服务名,必须要有

如果启动报错,找不到hystrix.stream,在你要监控的微服务加入如下配置。

management:
  endpoints:
    web:
      exposure:
        include: '*'
  • 3 修改主类

@EnableTurbine ,@EnableHystrixDashboard 一个都不能少

@EnableDiscoveryClient
@SpringBootApplication
@EnableTurbine
@EnableHystrixDashboard
public class Sb2scDashboardApplication {
    public static void main(String[] args) {
        SpringApplication.run(Sb2scDashboardApplication.class, args);
    }
}
  • 4 访问测试

这块的端口是8900,访问地址http://localhost:8900/hystrix,看到的是下面的页面。

13.png

然后在那个网址的输入框里输网址http://localhost:8900/turbine.stream,点击monitor stream。刚打开的时候可能是空的,什么也没有,这并不表示你已经错了。这时候你访问消费者服务的接口,例如访问http://localhost:8400/consumer/feign/list,多访问几次,然后看控制台有没有出现一个监控面板,没有就等会刷新一次,如果一直不出现,应该是配置有问题。

12.png

七、使用sleuth+zipkin 实现链路追踪服务

在使用微服务的时候,我们发现,有时候排错不好排查,所以就给大家整个这个链路追踪,很方便知道是哪一个服务调用哪一个服务出现了问题。因为有些项目可能服务比较多。

  • 1 添加依赖

新建一个springboot项目
虽然其他服务调用zipkin不是从eureka上动态过去服务地址,而是硬编码,但是这块还是考虑吧zipkin注册到eureka上。

compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')
compile group: 'io.zipkin.java', name: 'zipkin-server', version: '2.9.3'
compile group: 'io.zipkin.java', name: 'zipkin-autoconfigure-ui', version: '2.9.3'
compile('org.springframework.boot:spring-boot-starter-actuator')

如果提示log4j有冲突,要排除依赖

configurations {
    compile.exclude module: 'log4j'
    compile.exclude module: 'slf4j-log4j12'
    compile.exclude module: 'spring-boot-starter-logging'
}
  • 2 修改application配置文件
server:
  port: 9411
spring:
  application:
    name: sc-sc-zipkin
  profiles:
    active: csdn
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
      instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
      ip-address: true
management:
  metrics:
    web:
      server:
        auto-time-requests: false
  • 3 主类注解添加

@EnableZipkinServer 主要是这个注解
启动服务后访问http://localhost:9411,就可以打开zipkin的控制台页面,这时候应该是什么都没有

@EnableDiscoveryClient
@SpringBootApplication
@EnableZipkinServer
public class Sb2scZipkinApplication {
    public static void main(String[] args) {
        SpringApplication.run(Sb2scZipkinApplication.class, args);
    }
}
  • 4 其他服务中调用

这里我们在消费者服务和提供者服务里都加入如下依赖

compile('org.springframework.cloud:spring-cloud-starter-sleuth')
compile('org.springframework.cloud:spring-cloud-starter-zipkin')

然后修改配置文件,bootstrap.yml、
这块zipkin的地址是硬编码的,目前还没发现怎么从服务注册中心eureka上动态获取,以后有解决方案,会更新帖子
sleuth这个是配置提取率,可以配置也可以不配置

spring:
  zipkin:
    base-url: http://localhost:9411
  sleuth:
    sampler:
      percentage: 1.0

启动服务,然后访问消费者服务的接口,这时候访问zipkin的控制台http://localhost:9411

14.png

点击依赖分析,可以看到调用服务链,因为这块只涉及到两个服务,所以只有两个,在实际生产环境中,这块可能有很多,到时候看起来就特别直观了。

微信截图_20180811123550.png
微信截图_20180811123512.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容