SpringCloud 之 配置服务器 及 Bus 消息总线(五)

项目文件:下载 358KB,可以用于 对比文件 及 目录结构,提前 查看效果。
上文传送地址:Hystrix 断路器聚合监控 [ Turbine ]

一、为什么用配置服务器。

有时候,微服务要做集群,这就意味着,会有多个微服务实例。 在业务上有时候需要修改一些配置信息,比如说 版本信息吧,倘若没有配置服务, 那么就需要挨个修改微服务,挨个重新部署微服务,这样就比较麻烦。
为了偷懒, 这些配置信息就会放在一个公共的地方,比如 git,然后通过配置服务器把它获取下来,然后微服务再从配置服务器上取下来。
这样只要修改 git 上的信息,那么同一个集群里的所有微服务都立即获取相应信息了,这样就大大节约了开发,上线和重新部署的时间了。

二、在 GitHub 上创建一个配置储存库。

在这里插入图片描述在这里插入图片描述
输入 respo,然后 /,然后输入 linze-view-service-feign-dev.yml,respo 就视为文件夹啦。

version: linze springcloud version 2.6

文件名格式为:" 项目名 " + " -dev.yml "。
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
在这里插入图片描述

三、创建子工程 linze-config-server 配置服务(配置服务器)。

3.1 工程创建。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.2 文件配置。

3.2.0 编辑 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>cn.lz</groupId>
        <artifactId>cloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>config-server</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

</project>

3.2.1 编辑 application.yml。

server:
  port: 8030
spring:
  application:
    name: linze-config-server
  cloud:
    config:
      # 分支
      label: master
      server:
        git:
          # Git 地址
          uri: https://github.com/LOVELINESSLYT/LinZeCloudConfigServer
          # 目录
          searchPaths: respo
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

3.2.2 编辑 ConfigServerApplication 启动类。

@EnableConfigServer 表示本 SpringBoot / 工程 是个配置服务器。

package cn.lz.cloud.configserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableConfigServer
@EnableDiscoveryClient
@EnableEurekaClient
public class ConfigServerApplication {

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

}

依次启动

EurekaServerApplication、ConfigServerApplication

访问 http://localhost:8030/version/dev,如下图。
在这里插入图片描述
这边并没有获取 git 中的文件信息,接下来我们要通过客户端去访问。

四、改造 linze-view-service-fegin 微服务(配置客户端)。

4.1 编辑 pom.xml。

spring-cloud-starter-config 用于访问配置服务器

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

4.2 创建 bootstrap.yml。

spring:
  cloud:
    config:
      label: master
      profile: dev
      discovery:
        enabled: true
        serviceId: linze-config-server
  # 注册到服务中心
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

4.3 编辑 application.yml。

这个文件没什么变化,就是将 eureka 地址信息移动到了 bootstrap.yml 里。

# server.port 就不设置了,因为要启动多个端口,如 8011、8012、8013 ...... 。

# Spring的配置
spring:
  application:
    # 视图微服务名称
    name: linze-view-service-feign
  zipkin:
    base-url: http://localhost:9411
  # 模板引擎配置
  profiles: default
  freemarker:
    template-loader-path: classpath:/templates/views/ftl/
    cache: false
    check-template-location: true
    content-type: text/html; charset=UTF-8
    expose-request-attributes: true
    expose-session-attributes: true
    request-context-attribute: request
    suffix: .ftl
# 开启断路器
feign:
  hystrix:
    enabled: true
# 路径访问允许
management:
  endpoints:
    web:
      exposure:
        include: "*"
      cors:
        allowed-origins: "*"
        allowed-methods: "*"

4.4 编辑 BugsController 控制器。

新增了获取版本信息。

package cn.lz.cloud.viewservicefeign.controller;

import cn.lz.cloud.viewservicefeign.service.BugsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by IntelliJ IDEA.
 *
 * @author NingZe
 * description:
 * path: LinZeCloud-cn.lz.cloud.viewservicefeign.controller-BugsController
 * date: 2019/11/14 0014 15:10
 * version: 02.06
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RefreshScope
public class BugsController {

    @Value("${version}")
    String version;

    @Value("${server.port}")
    String port;

    @Autowired
    BugsService bs;

    @RequestMapping("bugs")
    public String bugs(Model model) {
        model.addAttribute("bugs", bs.listBugs());
        model.addAttribute("port", port);
        model.addAttribute("version", version);
        return "bugs";
    }

}

4.5 编辑 bugs.ftl 模板。

新增了获取版本信息。

<tr>
    <th align="center" colspan="4">
        ${version}
    </th>
</tr>

完整 ftl 文件。

<#--
  Created by IntelliJ IDEA.
  User: NingZe
  Date: 2019/11/13 0013
  Time: 09:39
  To change this template use File | Settings | File Templates.
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>bugs</title>
</head>
<style>

    table {
        border-collapse: collapse;
        width: 450px;
        margin: 20px auto;
        height: 235px;
        font-family: SimSun;
        font-size: 14px;
    }

    td, th {
        border: 1px solid gray;
    }

</style>
<body>

<table>
    <tr>
        <th>装备编号</th>
        <th>装备名称</th>
        <th>装备价格</th>
        <th>数据微服务端口</th>
    </tr>
    <#list bugs as b>
        <tr>
            <th>${b.bid}</th>
            <th>${b.bname}</th>
            <th>${b.bprice}</th>
            <th>${b.bport}</th>
        </tr>
    </#list>
    <tr>
        <th align="center" colspan="2">
            视图微服务端口
        </th>
        <th align="center" colspan="2">
            ${port}
        </th>
    </tr>
    <tr>
        <th align="center" colspan="4">
            ${.now}
        </th>
    </tr>
    <tr>
        <th align="center" colspan="4">
            ${version}
        </th>
    </tr>
</table>

</body>
</html>

4.6 启动并访问。

依次启动

EurekaServerApplication、ConfigServerApplication
DataServiceApplication8001、ViewServiceFeignApplication8011
ZuulServiceApplication

访问 http://localhost:8026/api-view/bugs,可以看到版本号,如下图。
在这里插入图片描述

4.7 刷新文件并访问。

手动修改文件。

version: linze springcloud version 6.6

在这里插入图片描述

在这里插入图片描述
再次访问 http://localhost:8026/api-view/bugs,可以看到版本号,并未发生改变,如下图。
在这里插入图片描述
必须重启,客户端。

ViewServiceFeignApplication8011

重启后才会生效,结果如下图。
在这里插入图片描述
所以接下来就要讲解如何通过 RabbitMQ 动态刷新啦。

五、消息总线 Bus。

继续改造 linze-view-service-feign 视图微服务。

5.0 安装 RabbitMQ。

2019 - RabbitMQ 消息中间件安装教程

5.1 编辑 pom.xml。

spring-boot-starter-actuator 用于访问路径:/actuator/bus-refresh
spring-cloud-starter-bus-amqp 用于支持 rabbitmq

<!-- 加过 actuator 了就不用加了。-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

5.2 编辑 bootstrap.yml。

新增 but 总线配置

    bus:
      enabled: true
      trace:
        enabled: true

新增 rabbitMQ 配置

  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest 

完整 bootstrap.yml 配置

# spring 配置
spring:
  cloud:
    # 服务器 - 客户端
    config:
      label: master
      profile: dev
      discovery:
        enabled: true
        serviceId: linze-config-server
    # bus总线配置
    bus:
      enabled: true
      trace:
        enabled: true
  # eureka 配置
  client:
    serviceUrl:
      defaultZone:  http://localhost:8761/eureka/
  # rabbitMQ 配置
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

5.3 编辑 application.yml。

新增路径访问允许,这样才能访问 /actuator/bus-refresh,加过了就不用加了

management:
  endpoints:
    web:
      exposure:
        include: "*"
      cors:
        allowed-origins: "*"
        allowed-methods: "*"

完整 application.yml 配置

# server.port 就不设置了,因为要启动多个端口,如 8011、8012、8013 ...... 。

# Spring的配置
spring:
  application:
    # 视图微服务名称
    name: linze-view-service-feign
  zipkin:
    base-url: http://localhost:9411
  # 模板引擎配置
  profiles: default
  freemarker:
    template-loader-path: classpath:/templates/views/ftl/
    cache: false
    check-template-location: true
    content-type: text/html; charset=UTF-8
    expose-request-attributes: true
    expose-session-attributes: true
    request-context-attribute: request
    suffix: .ftl
# 开启断路器
feign:
  hystrix:
    enabled: true
# 路径访问允许
management:
  endpoints:
    web:
      exposure:
        include: "*"
      cors:
        allowed-origins: "*"
        allowed-methods: "*"

5.4 编辑 ViewServiceFeignApplication 启动类。

新增 RabbitMQ 端口检测。

package cn.lz.cloud.viewservicefeign;

import brave.sampler.Sampler;
import cn.hutool.core.net.NetUtil;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
public class ViewServiceFeignApplication {

    public static void main(String[] args) {
        // 判断 rabiitMQ 是否启动
        int rabbitMQPort = 5672;
        if (!NetUtil.isUsableLocalPort(rabbitMQPort)) {
            System.err.printf("未在端口%d 发现 rabbitMQ 服务,请检查 rabbitMQ 是否启动 %n", rabbitMQPort);
            System.exit(1);
        }
        // 因为要启动多个,例如 8111、8012、8013 ......
        // 所以采用自动切换端口,去启动,启动的时候我们等待第一个启动完成后,在启动第二个
        int port = 8011;
        for (int i = 1; i <= 9; i++) {
            port = Integer.parseInt(801 + "" + i);
            if (!NetUtil.isUsableLocalPort(port)) {
                System.err.printf("端口%d被占用了,无法正常启动,正在更换端口,请稍等片刻...... %n", port);
                if (port == 8019) {
                    System.exit(1);
                }
                continue;
            }
            break;
        }
        System.out.printf("端口%d,启动中...... %n", port);
        new SpringApplicationBuilder(ViewServiceFeignApplication.class).properties("server.port=" + port).run(args);
    }

    @Bean
    public Sampler defaultSampler() {
        return Sampler.ALWAYS_SAMPLE;
    }

}

5.5 创建 RefreshConfigUtil 刷新配置类。

注:因为 /actuator/bus-refresh 不支持 get 访问,当然可以用 Postman 以及 Ajax 等 模拟 post 去访问。
本文采用的是在 linze-publics/util 下创建类去访问。

package cn.lz.cloud.publics.util;

import cn.hutool.http.HttpUtil;

import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 *
 * @author NingZe
 * description:
 * path: cloud-cn.lz.cloud.publics.util-RefreshConfigUtil
 * date: 2019/11/26 0026 13:46
 * version: 02.06
 * To change this template use File | Settings | File Templates.
 */
public class RefreshConfigUtil {

    public static void main(String[] args) {
        HashMap<String,String> headers = new HashMap<>(1);
        headers.put("Content-Type", "application/json; charset=utf-8");
        System.out.println("因为要去git获取,还要刷新 linze-config-server, 会比较卡,所以一般会要好几秒才能完成,请耐心等待......");
        Long l1 = System.currentTimeMillis();
        HttpUtil.createPost("http://localhost:8026/api-view/actuator/bus-refresh").addHeaders(headers).execute().body();
        Long l2 = System.currentTimeMillis();
        System.out.println("耗时:" + (l2 - l1) + "ms.");
        System.out.println("refresh 完成.");
    }

}

当我们修改github上 linze-view-service-feign 的配置后,运行 RefreshConfigUtil 去访问 /actuator/bus-refresh,就可以动态刷新啦。

5.6 启动并访问。

依次启动

EurekaServerApplication、ConfigServerApplication
DataServiceApplication8001、ViewServiceFeignApplication8011
ZuulServiceApplication、TurbineServiceApplication

1. 首先访问 http://localhost:8026/api-view/bugs,查看一次版本,如下图为 6.6 版本。
在这里插入图片描述
2. 然后我们改为 5.5 版本。
在这里插入图片描述
3. 然后运行 RefreshConfigUtil 刷新类。在这里插入图片描述
4. 然后再次访问 http://localhost:8026/api-view/bugs,如下图更为了 5.5 版本啦,成功使用 rabbitMQ 完成了动态刷新。
在这里插入图片描述

5.7 对服务链路追踪的影响。

因为视图服务进行了改造,支持了 rabbitMQ, 那么在默认情况下,它的信息就不会进入 Zipkin 了,也看不到视图服务的资料了。
本来是

java -jar zipkin-server-2.12.9-exec.jar

现在是

java -jar zipkin-server-2.12.9-exec.jar --zipkin.collector.rabbitmq.addresses=localhost
注:重启 zipkin 后,要再访问业务地址才可以看到依赖关系。

在这里插入图片描述

本文到此结束,2019.11.26,下一篇 [ IDAE 项目提交到 GitHub ] ,待续 。。。。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值