SpringCloud Hoxton SR8,系统一套第二天,看完不说精通,至少自己能完整搭建起来

1,285 阅读14分钟

使用网关统一入口访问

简介

​ 路由是微服务架构不可或缺的一部分。例如,/可能被映射到您的Web应用程序,/ api / users被映射到用户服务,而/ api / shop被映射到shop服务。Zuul是Netflix提供的基于JVM的路由器和服务器端负载平衡器。这里先介绍Zuul的使用方式。GateWay的在Alibaba的时候再说。

Netflix将Zuul用于以下用途:(以下翻译来自官网)

  • 认证方式

  • 见解

  • 压力测试

  • 灰度发布测试

  • 动态路由

  • 服务迁移

  • 减载

  • 安全

  • 静态响应处理

  • 主动/主动流量管理

创建路由网关

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>com.wujie</groupId>
        <artifactId>hello-spring-cloud-dependencies</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <groupId>com.wujie</groupId>
    <artifactId>hello-spring-cloud-zuul</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hello-spring-cloud-zuul</name>
    <description>创建路由网关</description>



    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>




    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
                <configuration>
                    <mainClass>com.wujie.hello.spring.cloud.zuul.HelloSpringCloudZuulApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

spring:
  application:
    name: hello-spring-cloud-zuul


server:
  port: 8766
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
zuul:
  routes:
    ribbon:
      path: /ribbon/**
      serviceId: HELLO-SPRING-CLOUD-WEB-ADMIN-RIBBON
      stripPrefix: true
    fegin:
      path: /fegin/**
      serviceId: HELLO-SPRING-CLOUD-WEB-ADMIN-FEGIN
      stripPrefix: true

在启动类上加上@EnableZuulProxy注解并启动

@SpringBootApplication
@EnableZuulProxy
public class HelloSpringCloudZuulApplication {

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

}

分别访问:对fegin和ribbon以及admin返回简单做了修改,显示端口让我们能够清晰的看见确实转发成功

http://localhost:8766/ribbon/hi?message=helloCloud

image-20200904204338029

http://localhost:8766/fegin/hi?message=helloCloud

image-20200904204441360

配置网关路由失败时的回调

当Zuul中给定路由的熔断时,可以通过创建FallbackProvider类型的bean提供回退响应。在此bean中,您需要指定回退用于的路由ID,并提供ClientHttpResponse作为回退返回。以下示例显示了一个相对简单的FallbackProvider实现:

@Component
public class WebAdminRoutesFallbackProvider implements FallbackProvider {
    @Override
    public String getRoute() {
        // ServiceId,如果需要所有调用都支持回退,则 return "*" 或 return null
//        return "HELLO-SPRING-CLOUD-WEB-ADMIN-FEGIN";
        return null;
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, final Throwable cause) {
        if (cause instanceof HystrixTimeoutException) {
            return response(HttpStatus.GATEWAY_TIMEOUT);
        } else {
            return response(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private ClientHttpResponse response(final HttpStatus status) {
        return new ClientHttpResponse() {
            /**
             * 网关向 api 服务请求失败了,但是消费者客户端向网关发起的请求是成功的,
             * 不应该把 api 的 404,500 等问题抛给客户端
             * 网关和 api 服务集群对于客户端来说是黑盒
             * @return
             * @throws IOException
             */
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return status;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return status.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return status.getReasonPhrase();
            }

            @Override
            public void close() {
            }

            @Override
            public InputStream getBody() throws IOException {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> map = new HashMap<>();
                map.put("status", 200);
                map.put("message", "无法连接,请检查您的网络");
                return new ByteArrayInputStream(objectMapper.writeValueAsString(map).getBytes("UTF-8"));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                // 和 getBody 中的内容编码一致
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}

如果您想为所有路由提供默认回退,则可以创建FallbackProvider类型的Bean,并让getRoute方法返回*或null。

自定义网关路由过滤器

@Component
public class LoginFilter extends ZuulFilter {
    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);
    /**
     * 配置过滤类型,有四种不同生命周期的过滤器类型
     * 1. pre:路由之前
     * 2. routing:路由之时
     * 3. post:路由之后
     * 4. error:发送错误调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }
    /**
     * 配置过滤的顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }
    /**
     * 配置是否需要过滤:true/需要,false/不需要
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }
    /**
     * 过滤器的具体业务代码
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String auth = request.getHeader("auth");
        logger.info("{} >>> {}", request.getMethod(), request.getRequestURL().toString());
        if (!StringUtils.isNotBlank(auth)) {
            logger.warn("权限认证失败");
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            context.getResponse().setCharacterEncoding("UTF-8");
            context.getResponse().setContentType("text/html;cahrset=UTF-8");
            try {
                context.getResponse().getWriter().write("权限认证失败");
            } catch (IOException e) {
            }
        } else {
            logger.info("OK");
        }
        return null;
    }
}

注意:当返回中文提示时,需要加上

context.getResponse().setCharacterEncoding("UTF-8");
context.getResponse().setContentType("text/html;cahrset=UTF-8");

否则会出现中文乱码

自定义好后,我们重启项目

第一次不加头信息访问:http://localhost:8766/ribbon/hi?message=helloCloud提示权限认证失败

image-20200904211731194

第二次加头信息访问:http://localhost:8766/ribbon/hi?message=helloCloud就返回正确的结果信息

image-20200904211833207

配置中心

简介

​ Spring Cloud Config为分布式系统中的外部化配置提供服务器端和客户端支持。使用Config Server,您可以在中心位置管理所有环境中应用程序的外部属性。客户端和服务器上的概念与Spring Environment和PropertySource抽象完全相同,因此它们非常适合Spring应用程序,但可以与以任何语言运行的任何应用程序一起使用。在应用程序从开发人员到测试人员再到生产人员的整个部署管道中进行移动时,您可以管理这些环境之间的配置,并确保应用程序具有它们迁移时所需的一切。服务器存储后端的默认实现使用git,因此它可以轻松支持配置环境的标记版本,并且可以通过各种工具来访问这些内容来管理内容。添加替代实现并将其插入Spring配置很容易。

创建配置中心服务端

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>com.wujie</groupId>
        <artifactId>hello-spring-cloud-dependencies</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <groupId>com.wujie</groupId>
    <artifactId>hello-spring-cloud-config</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hello-spring-cloud-config</name>
    <description>创建配置文件中心</description>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
                <configuration>
                    <mainClass>com.wujie.hello.spring.cloud.config.HelloSpringCloudConfigApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

spring:
  application:
    name: hello-spring-cloud-config
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/wujiele/respo.git
          search-paths:  reps
          username:
          password:


server:
  port: 8888
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

相关配置说明,如下:

  • spring.cloud.config.label:配置仓库的分支
  • spring.cloud.config.server.git.uri:配置 Git 仓库地址(GitHub、GitLab、码云 ...)
  • spring.cloud.config.server.git.search-paths:配置仓库路径(存放配置文件的目录)
  • spring.cloud.config.server.git.username:访问 Git 仓库的账号
  • spring.cloud.config.server.git.password:访问 Git 仓库的密码

注意事项:

  • 如果使用 GitLab 作为仓库的话,git.uri 需要在结尾加上 .git,GitHub 则不用

在启动类上加上注解@EnableConfigServer开启配置中心服务

@SpringBootApplication
@EnableConfigServer
public class HelloSpringCloudConfigApplication {

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

}

启动项目访问:http://localhost:8888/config-client/dev/master如下图:

image-20200904213743949

附:HTTP 请求地址和资源文件映射

创建配置中心客户端

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>com.wujie</groupId>
        <artifactId>hello-spring-cloud-dependencies</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <groupId>com.wujie</groupId>
    <artifactId>hello-spring-cloud-config-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hello-spring-cloud-config-client</name>
    <description>创建配置文件客户端</description>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
                <configuration>
                    <mainClass>com.wujie.hello.spring.cloud.config.client.HelloSpringCloudConfigClientApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

spring:
  application:
    name: hello-spring-cloud-config-client
  cloud:
    config:
      uri: http://localhost:8888
      name: config-client
      label: master
      profile: dev

server:
  port: 8889

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

相关配置说明,如下:

  • spring.cloud.config.uri:配置服务中心的网址

  • spring.cloud.config.name:配置文件名称的前缀

  • spring.cloud.config.label:配置仓库的分支

  • spring.cloud.config.profile
    

    :配置文件的环境标识

    • dev:表示开发环境
    • test:表示测试环境
    • prod:表示生产环境

注意:配置服务器的默认端口为 8888,如果修改了默认端口,则客户端项目就不能在 application.ymlapplication.properties 中配置 spring.cloud.config.uri,必须在 bootstrap.yml 或是 bootstrap.properties 中配置,原因是 bootstrap 开头的配置文件会被优先加载和配置,切记

创建TestController测试类

@RestController
public class TestController {
    @Value("${wujie}")
    private String name;

    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String hi() {
        return name;
    }
}

启动类上添加@EnableDiscoveryClient注解开启服务

在启动完成后会看见我们的端口号与配置文件里的不一样了,这是因为我在远程重新配置了端口号

image-20200904220819149

image-20200904220851918

使用新的端口号访问http://localhost:7010/hi

image-20200904220958492

返回与远程配置一样,则证明配置成功。

服务链路追踪

简介

Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud.

Spring Cloud Sleuth为Spring Cloud实现了分布式跟踪解决方案。

术语

Spring Cloud Sleuth borrows Dapper’s terminology.

Spring Cloud Sleuth借鉴了Dapper的术语。

Span: The basic unit of work. For example, sending an RPC is a new span, as is sending a response to an RPC. Spans are identified by a unique 64-bit ID for the span and another 64-bit ID for the trace the span is a part of. Spans also have other data, such as descriptions, timestamped events, key-value annotations (tags), the ID of the span that caused them, and process IDs (normally IP addresses).

Span:工作的基本单位。例如,发送RPC是新的跨度,就像发送响应到RPC一样。跨度由跨度的唯一64位ID和跨度所属的跟踪的另一个64位ID标识。跨区还具有其他数据,例如描述,带有时间戳的事件,键值批注(标签),引起跨度的跨区ID和进程ID(通常为IP地址)

Trace: A set of spans forming a tree-like structure. For example, if you run a distributed big-data store, a trace might be formed by a PUT request.

**Trace:**一组形成树状结构的跨度。例如,如果运行分布式大数据存储,则跟踪可能由PUT请求形成。

Annotation: Used to record the existence of an event in time. With Brave instrumentation, we no longer need to set special events for Zipkin to understand who the client and server are, where the request started, and where it ended. For learning purposes, however, we mark these events to highlight what kind of an action took place.

  • cs: Client Sent. The client has made a request. This annotation indicates the start of the span.
  • sr: Server Received: The server side got the request and started processing it. Subtracting the cs timestamp from this timestamp reveals the network latency.
  • ss: Server Sent. Annotated upon completion of request processing (when the response got sent back to the client). Subtracting the sr timestamp from this timestamp reveals the time needed by the server side to process the request.
  • cr: Client Received. Signifies the end of the span. The client has successfully received the response from the server side. Subtracting the cs timestamp from this timestamp reveals the whole time needed by the client to receive the response from the server.

**Annotation:**用于及时记录事件的存在。使用Brave工具,我们不再需要为Zipkin设置特殊事件来了解客户端和服务器是谁,请求在哪里开始以及在哪里结束。但是,出于学习目的,我们标记这些事件以突出显示发生了哪种操作。

  • cs:客户端已发送。客户提出了要求。此注释指示跨度的开始。
  • sr:收到服务器:服务器端收到请求并开始处理它。从该时间戳减去cs时间戳可揭示网络延迟。
  • ss:服务器已发送。在请求处理完成时添加注释(当响应被发送回客户端时)。从此时间戳中减去sr时间戳可显示服务器端处理请求所需的时间。
  • cr:收到客户。表示跨度结束。客户端已成功收到服务器端的响应。从此时间戳中减去cs时间戳可显示出客户端从服务器接收响应所需的整个时间。

Zipkin简介

ZipKin 是一个开放源代码的分布式跟踪系统,由 Twitter 公司开源,它致力于收集服务的定时数据,以解决微服务架构中的延迟问题,包括数据的收集、存储、查找和展现。它的理论模型来自于 Google Dapper 论文。

每个服务向 ZipKin 报告计时数据,ZipKin 会根据调用关系通过 ZipKin UI 生成依赖关系图,显示了多少跟踪请求通过每个服务,该系统让开发者可通过一个 Web 前端轻松的收集和分析数据,例如用户每次请求服务的处理时间等,可方便的监测系统中存在的瓶颈。

将 Span 和 Trace 在一个系统中使用 Zipkin 注解的过程图形化:

![Zipkin 注解的过程](wujiele.gitee.io/image/Zipki… 注解的过程.png)

创建 ZipKin 服务端

Zipkin共有三种运行方式,java、docker、以及源码编译。我这里就直接使用java的方式,感兴趣的可以自行去官网查看别的方式:

在SpringBoot 2.0版本以后已经不需要自行搭建zipkin-server,而是直接使用官方提供的编译好的jar包,在终端使用以下命令下载并启动zipkin-server

curl -sSL https://zipkin.io/quickstart.sh | bash -s
java -jar zipkin.jar

使用java命令运行起来以后可以访问http://localhost:9411查看界面

image-20200905104408566

在想要追踪的项目里加上依赖,并在配置文件中加入配置

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zipkin</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>
zipkin:
  base-url: http://localhost:9411

然后重启项目,将之前写的接口测试一下,就可以在zipkin中进行查看

image-20200905111628342

image-20200905111658828

image-20200905111741633

至此就代表zipkin配置成功。

监控系统

简介

​ 随着开发周期的推移,项目会不断变大,切分出的服务也会越来越多,这时一个个的微服务构成了错综复杂的系统。对于各个微服务系统的健康状态、会话数量、并发数、服务资源、延迟等度量信息的收集就成为了一个挑战。Spring Boot Admin 应运而生,它正式基于这些需求开发出的一套功能强大的监控管理系统。

Spring Boot Admin provides the following features for registered applications:

  • Show health status
  • Show details, like
    • JVM & memory metrics
    • micrometer.io metrics
    • Datasource metrics
    • Cache metrics
  • Show build-info number
  • Follow and download logfile
  • View jvm system- & environment-properties
  • View Spring Boot Configuration Properties
  • Support for Spring Cloud's postable /env- &/refresh-endpoint
  • Easy loglevel management
  • Interact with JMX-beans
  • View thread dump
  • View http-traces
  • View auditevents
  • View http-endpoints
  • View scheduled tasks
  • View and delete active sessions (using spring-session)
  • View Flyway / Liquibase database migrations
  • Download heapdump
  • Notification on status change (via e-mail, Slack, Hipchat, ...)
  • Event journal of status changes (non persistent)

Spring Boot Admin为注册的应用程序提供以下功能:

  • 显示健康状况
  • 显示详细信息,例如
    • JVM和内存指标
    • micrometer.io 指标
    • 数据源指标
    • 缓存指标
  • 显示构建信息编号
  • 关注并下载日志文件
  • 查看JVM系统和环境属性
  • 查看Spring Boot配置属性
  • 支持Spring Cloud的可发布/ env-&/ refresh-endpoint
  • 轻松的日志级别管理
  • 与JMX-beans交互
  • 查看线程垃圾
  • 查看http痕迹
  • 查看审核事件
  • 查看http端点
  • 查看定时任务
  • 查看和删除活动会话(使用spring-session)
  • 查看Flyway / Liquibase数据库迁移
  • 下载堆内存
  • 状态更改通知(通过电子邮件,Slack,Hipchat等)
  • 状态更改的事件日志(非持久性)

Spring Boot Admin 有两个角色组成,一个是 Spring Boot Admin Server,一个是 Spring Boot Admin Client,本章节将带领大家实现 Spring Boot Admin 的搭建。

Spring Boot Admin服务端

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>com.wujie</groupId>
        <artifactId>hello-spring-cloud-dependencies</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <groupId>com.wujie</groupId>
    <artifactId>hello-spring-cloud-admin</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hello-spring-cloud-admin</name>
    <description>SpringBootAdmin服务端</description>



    <dependencies>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>2.3.0</version>
        </dependency>
        <!-- Spring Cloud Begin -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
        <!-- Spring Cloud End -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
                <configuration>
                    <mainClass>com.wujie.hello.spring.cloud.admin.HelloSpringCloudAdminApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

spring:
  application:
    name: hello-spring-cloud-admin
  zipkin:
    base-url: http://localhost:9411
server:
  port: 8767
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

在启动类上加上@EnableAdminServer注解,然后启动

@SpringBootApplication
@EnableAdminServer
public class HelloSpringCloudAdminApplication {

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

}

访问http://localhost:8767即可看见如图说明成功

image-20200905115119910

SpringBootAdmin客户端

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>com.wujie</groupId>
        <artifactId>hello-spring-cloud-dependencies</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <groupId>com.wujie</groupId>
    <artifactId>hello-spring-cloud-admin-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hello-spring-cloud-admin-client</name>
    <description>Spring Boot Admin客户端</description>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
                <configuration>
                    <mainClass>com.wujie.hello.spring.cloud.admin.client.HelloSpringCloudAdminClientApplication
                    </mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

spring:
  application:
    name: hello-spring-cloud-admin-client
  boot:
    admin:
      client:
        url: http://localhost:8767
  zipkin:
    base-url: http://localhost:9411

server:
  port: 8768

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: ALWAYS

注意:

management: endpoints: web: exposure: include: '*' endpoint: health: show-details: ALWAYS

这个是配置在客户端,才可以显示信息。网上很多放在服务端,结果访问就什么信息都没有就像下面这张图

image-20200905123651901

如果配置正确就会是这样的

image-20200905123723835

至此,也就配置成功了。

心得

​ 不管是对于微服务还是其他什么技术,我们只有抱着谦虚的态度去学习,去摸索才能够从中得到自己想要的知识,另外也不要畏惧英文文献,不管在百度还是Google上去搜索的永远都是第二手第三手甚至第N手的资料,官方才是最新的第一手资料,甚至各个版本的都有,但是大多数都是英文,此时我们不能畏惧学习,网上翻译软件如此之多,我们先自己尝试着阅读再去使用翻译软件进行翻译,结合自己的行业的理解,基本上也是八九不离十了。这样做的好处在于我们可以进一步提升自己的英语水平,还可以对文档至少有三遍的记忆(自己先尝试翻译、使用翻译软件翻译、做笔记),也会加深我们对于此技术的认知。

古人云温故而知新可以为师矣

参考资料