Skip to content

quick start

liubao edited this page Jun 1, 2022 · 9 revisions

快速开始

微服务架构的好处之一就是开发新的应用变得更加快速和简单。达成这个目标的主要原因是微服务 基础设施已经由微服务平台和微服务框架实现了,从开发者而言,微服务的应用架构、使用的技术栈 都变得更加简单。

Spring Cloud Huawei Samples 提供了一个典型的微服务架构应用, 它包括微服务网关、微服务提供者和微服务消费者三个微服务。通过下载该项目,就实现了快速搭建 具备简单功能的微服务应用。

微服务网关

微服务网关是请求的入口,也是实现弹性架构最常用的组件。引入微服务网关,既可以通过限制请求的入口 达到提升应用安全的目的,也可以通过屏蔽内部微服务应用的架构细节,实现微服务的持续重构(拆分和合并等)。 微服务网关在解决夸子系统访问等其他应用场景也有非常重要的作用。

微服务网关开发最重要的配置路由规则和启用服务治理。本示例的路由规则如下:

spring:
  cloud:
    gateway:
      routes:
        - id: consumer
          uri: lb://basic-consumer
          filters:
            - name: governance
          predicates:
            - Path=/**

该路由规则将所有请求 /** 转发到 basic-consumer 微服务。 并启用了服务治理,在filters里面配置。 Spring Cloud Huawei提供的服务治理名称为 governance

本示例启用了服务治理,并配置了简单的流控规则:

servicecomb:
  matchGroup:
    allOperation: |
      matches:
        - apiPath:
            prefix: "/"
  rateLimiting:
    allOperation: |
      rate: 100

流控规则限制所有请求的流量是100TPS。

微服务提供者

微服务提供者实现了一个REST服务,

@RestController
public class ProviderController {
  // a very simple service to echo the request parameter
  @GetMapping("/sayHello")
  public String sayHello(@RequestParam("name") String name) {
    return "Hello " + name;
  }
  @GetMapping("/sayHelloFeign")
  public String sayHelloFeign(@RequestParam("name") String name) {
    return "Hello " + name;
  }
}

该服务实现了两个简单的接口 /sayHello/sayHelloFeign

微服务消费者

微服务消费者演示了通过 RestTemplateFeign 两种方式访问微服务提供者,

@RestController
public class ConsumerController {
  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  private FeignConsumerService feignConsumerService;

  private ConfigListen configListen;

  @Autowired
  public ConsumerController(ConfigListen configListen) {
    this.configListen = configListen;
  }

  // consumer service which delegate the implementation to provider service.
  @GetMapping("/sayHello")
  public String sayHello(@RequestParam("name") String name) {
    return restTemplate.getForObject("http://basic-provider/sayHello?name={1}", String.class, name);
  }

  @GetMapping("/sayHelloFeign")
  public String sayHelloFeign(@RequestParam("name") String name) {
    return feignConsumerService.sayHelloFeign(name);
  }
}
Clone this wiki locally