springcloud总结下

八、Hystrix

1、简介

主页:https://github.com/Netflix/Hystrix/

image-20210927161946201

Hystix是Netflix开源的一个延迟和容错库,用于隔离访问远程服务,防止出现级联失败。

2、雪崩问题

微服务中,服务间调用关系错综复杂,一个请求,可能需要调用多个微服务接口才能实现,会形成非常复杂的调用 链路:

image-20210927162031242

如图,一次业务请求,需要调用A、P、H、I四个服务,这四个服务又可能调用其它服务。 如果此时,某个服务出 现异常:

image-20210927162050230

例如: 微服务I 发生异常,请求阻塞,用户请求就不会得到响应,则tomcat的这个线程不会释放,于是越来越多的 用户请求到来,越来越多的线程会阻塞:

image-20210927162114098

服务器支持的线程和并发数有限,请求一直阻塞,会导致服务器资源耗尽,从而导致所有其它服务都不可用,形成雪崩效应。 这就好比,一个汽车生产线,生产不同的汽车,需要使用不同的零件,如果某个零件因为种种原因无法使用,那么就会造成整台车无法装配,陷入等待零件的状态,直到零件到位,才能继续组装。 此时如果有很多个车型都需要这个零件,那么整个工厂都将陷入等待的状态,导致所有生产都陷入瘫痪。一个零件的波及范围不断扩大。 Hystrix解决雪崩问题的手段,主要包括:

①线程隔离 ②服务降级

3、线程隔离&服务降级

①原理

线程隔离示意图

image-20210927162231716

解读: Hystrix为每个依赖服务调用分配一个小的线程池,如果线程池已满调用将被立即拒绝,默认不采用排队,加速失败判定时间。 用户的请求将不再直接访问服务,而是通过线程池中的空闲线程来访问服务,如果线程池已满,或者请求超时,则会进行降级处理,什么是服务降级? 服务降级:可以优先保证核心服务。 用户的请求故障时,不会被阻塞,更不会无休止的等待或者看到系统崩溃,至少可以看到一个执行结果(例如返回友好的提示信息) 。

服务降级虽然会导致请求失败,但是不会导致阻塞,而且最多会影响这个依赖服务对应的线程池中的资源,对其它 服务没有响应。 触发Hystrix服务降级的情况:

①线程池已满 ②请求超时

②动手实践

服务降级:及时返回服务调用失败的结果,让线程不因为等待服务而阻塞

Ⅰ 引入依赖

在 consumer-demo 消费端系统的pom.xml文件添加如下依赖:

<!--熔断-->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

Ⅱ 开启熔断

在启动类 ConsumerApplication 上添加注解:@EnableCircuitBreaker

package com.lxs.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
// 开启Eureka客户端
@EnableEurekaClient
// 开启熔断
@EnableCircuitBreaker
public class ConsumerApplication {
   public static void main(String[] args) {
       SpringApplication.run(ConsumerApplication.class, args);
  }
   @Bean
   @LoadBalanced
   public RestTemplate restTemplate(){
       return new RestTemplate();
  }
}

可以看到,我们类上的注解越来越多,在微服务中,经常会引入上面的三个注解,于是Spring就提供了一个组合注 解:@SpringCloudApplication

image-20210927163814225

因此,我们可以使用这个组合注解来代替之前的3个注解 :

package com.lxs.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringCloudApplication
public class ConsumerApplication {
   public static void main(String[] args) {
       SpringApplication.run(ConsumerApplication.class, args);
  }
   @Bean
   @LoadBalanced
   public RestTemplate restTemplate(){
       return new RestTemplate();
  }
}

③编写降级逻辑

当目标服务的调用出现故障,我们希望快速失败,给用户一个友好提示。因此需要提前编写好失败时的降级处理逻辑,要使用HystrixCommand来完成。 改造 consumer-demo\src\main\java\lxs\com\consumer\controller\ConsumerController.java 处理器 类,如下:

package com.lxs.consumer.controller;

import com.lxs.consumer.pojo.User;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
@Slf4j
public class UserController {
   @Autowired
   private RestTemplate restTemplate;
   @Autowired
   private DiscoveryClient discoveryClient;

   @GetMapping("/{id}")
   @HystrixCommand(fallbackMethod = "queryByIdFallback")
   public String queryById(@PathVariable long id){
//       String url="http://localhost:9091/user/"+id;
//       List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//       ServiceInstance serviceInstance=instances.get(0);
//       url="http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/"+id;
       String url="http://user-service/user/"+id;
       return restTemplate.getForObject(url,String.class);
  }
   public String queryByIdFallback(long id) {
       log.error("查询用户信息失败。id:{}", id);
       return "对不起,网络太拥挤了!";
  }
}

注意:

因为熔断的降级逻辑方法必须跟正常逻辑方法保证:相同的参数列表和返回值声明。 失败逻辑中返回User对象没有太大意义,一般会返回友好提示。所以把queryById的方法改造为返回String,反正也是Json数据。这样失败逻辑中返回一个错误说明,会比较方便。

说明:

@HystrixCommand(fallbackMethod = "queryByIdFallBack"):用来声明一个降级逻辑的方法测试: 当 user-service 正常提供服务时,访问与以前一致。但是当将 user-service 停机时,会发现页面返回了降级处理信息:

image-20210927165312798

④默认的fallback

刚才把fallback写在了某个业务方法上,如果这样的方法很多,那岂不是要写很多。所以可以把Fallback配置加在 类上,实现默认fallback; 再次改造 consumerdemo\src\main\java\com\lxs\consumer\controller\ConsumerController.java

package com.lxs.consumer.controller;

import com.lxs.consumer.pojo.User;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallback")
public class UserController {
   @Autowired
   private RestTemplate restTemplate;
   @Autowired
   private DiscoveryClient discoveryClient;

   @GetMapping("/{id}")
//   @HystrixCommand(fallbackMethod = "queryByIdFallback")
   @HystrixCommand
   public String queryById(@PathVariable long id){
//       String url="http://localhost:9091/user/"+id;
//       List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//       ServiceInstance serviceInstance=instances.get(0);
//       url="http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/"+id;
       String url="http://user-service/user/"+id;
       return restTemplate.getForObject(url,String.class);
  }
   public String queryByIdFallback(long id) {
       log.error("查询用户信息失败。id:{}", id);
       return "对不起,网络太拥挤了!";
  }
   public String defaultFallback() {
       return "默认提示:对不起,网络太拥挤了!";
  }
}

@DefaultProperties(defaultFallback = "defaultFallBack"):在类上指明统一的失败降级方法;该类中所有 方法返回类型要与处理失败的方法的返回类型一致。

image-20210927165549947

⑤超时设置

在之前的案例中,请求在超过1秒后都会返回错误信息,这是因为Hystrix的默认超时时长为1,我们可以通过配置 修改这个值;修改 consumer-demo\src\main\resources\application.yml 添加如下配置:

spring:
application:
  name: consumer-demo
eureka:
client:
  service-url:
    defaultZone: HTTP://127.0.0.7:10086/eureka
   #每隔30秒则会从Eureka Server服务的列表拉取只读备份,然后缓存在本地。
  registry-fetch-interval-seconds:  30
user-service:
ribbon:
  NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
#超时设置
hystrix:
command:
  default:
    execution:
      isolation:
        thread:
          timeoutInMilliseconds: 2000

这个配置会作用于全局所有方法。为了方便复制到yml配置文件中。

为了触发超时,可以在 user-service\src\main\java\com\lxs\user\service\UserService.java 的方法中 休眠2秒;

package com.lxs.user.controller;

import com.lxs.user.pojo.User;
import com.lxs.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
//开启Eureka客户端发现功能
@EnableEurekaClient
public class UserController {
   @Autowired
   private UserService userService;
   @RequestMapping("/{id}")
   public User queryById(@PathVariable Long id) throws InterruptedException {
       Thread.sleep(2000);
       return userService.queryById(id);
  }
}

测试:

image-20210927165947795

可以发现,请求的时长已经到了2s+,证明配置生效了。如果把修改时间修改到2秒以下,又可以正常访问。

4、服务熔断

①熔断原理

在服务熔断中,使用的熔断器,也叫断路器,其英文单词为:Circuit Breaker 熔断机制与家里使用的电路熔断原理 类似;当如果电路发生短路的时候能立刻熔断电路,避免发生灾难。在分布式系统中应用服务熔断后;服务调用方 可以自己进行判断哪些服务反应慢或存在大量超时,可以针对这些服务进行主动熔断,防止整个系统被拖垮。 Hystrix的服务熔断机制,可以实现弹性容错;当服务请求情况好转之后,可以自动重连。通过断路的方式,将后续 请求直接拒绝,一段时间(默认5秒)之后允许部分请求通过,如果调用成功则回到断路器关闭状态,否则继续打 开,拒绝请求的服务。

Hystrix的熔断状态机模型:

image-20210927170752635

状态机有3个状态: Closed:关闭状态(断路器关闭),所有请求都正常访问。 Open:打开状态(断路器打开),所有请求都会被降级。Hystrix会对请求情况计数,当一定时间内失败请求百分比达到阈值,则触发熔断,断路器会完全打开。默认失败比例的阈值是50%,请求次数最少不低于20次。 Half Open:半开状态,不是永久的,断路器打开后会进入休眠时间(默认是5S)。随后断路器会自动进入半开状态。此时会释放部分请求通过,若这些请求都是健康的,则会关闭断路器,否则继续保持打开,再次进行休眠计时

分析图:

image-20210927170913966

②动手实践

为了能够精确控制请求的成功或失败,在 consumer-demo 的处理器业务方法中加入一段逻辑; 修改consumerdemo\src\main\java\com\lxs\consumer\controller\ConsumerController.java

package com.lxs.consumer.controller;

import com.lxs.consumer.pojo.User;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallback")
public class UserController {
   @Autowired
   private RestTemplate restTemplate;
   @Autowired
   private DiscoveryClient discoveryClient;

   @GetMapping("/{id}")
//   @HystrixCommand(fallbackMethod = "queryByIdFallback")
   @HystrixCommand
   public String queryById(@PathVariable long id){
       if (id == 1) {
           throw new RuntimeException("太忙了");
      }
//       String url="http://localhost:9091/user/"+id;
//       List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//       ServiceInstance serviceInstance=instances.get(0);
//       url="http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/"+id;
       String url="http://user-service/user/"+id;
       return restTemplate.getForObject(url,String.class);
  }
   public String queryByIdFallback(long id) {
       log.error("查询用户信息失败。id:{}", id);
       return "对不起,网络太拥挤了!";
  }
   public String defaultFallback() {
       return "默认提示:对不起,网络太拥挤了!";
  }
}

这样如果参数是id为1,一定失败,其它情况都成功。(不要忘了清空user-service中的休眠逻辑) 我们准备两个 请求窗口:

一个请求:http://localhost:8080/consumer/1,注定失败

一个请求:http://localhost:8080/consumer/2,肯定成功

当我们疯狂访问id为1的请求时(超过20次),就会触发熔断。断路器会打开,一切请求都会被降级处理。 此时你访问id为2的请求,会发现返回的也是失败,而且失败时间很短,只有20毫秒左右;因进入半开状态之后2是 可以的。

image-20210927171519718

不过,默认的熔断触发要求较高,休眠时间窗较短,为了测试方便,我们可以通过配置修改熔断策略:

spring:
application:
  name: consumer-demo
eureka:
client:
  service-url:
    defaultZone: HTTP://127.0.0.7:10086/eureka
   #每隔30秒则会从Eureka Server服务的列表拉取只读备份,然后缓存在本地。
  registry-fetch-interval-seconds:  30
user-service:
ribbon:
  NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
#超时设置
hystrix:
command:
  default:
    execution:
      isolation:
        thread:
          timeoutInMilliseconds: 2000
    circuitBreaker:
      errorThresholdPercentage: 50 # 触发熔断错误比例阈值,默认值50%
      sleepWindowInMilliseconds: 10000 # 熔断后休眠时长,默认值5秒
      requestVolumeThreshold: 10 # 熔断触发最小请求次数,默认值是20

上述的配置项可以参考 HystrixCommandProperties 类中。

九、Feign

在前面的学习中,我们使用了Ribbon的负载均衡功能,大大简化了远程调用时的代码:

String url="http://user-service/user/"+id;
return restTemplate.getForObject(url,String.class);

如果就学到这里,你可能以后需要编写类似的大量重复代码,格式基本相同,无非参数不一样。有没有更优雅的方式,来对这些代码再次优化呢? 这就是我们接下来要学的Feign的功能了。

1、简介

为什么叫伪装? Feign可以把Rest的请求进行隐藏,伪装成类似SpringMVC的Controller一样。你不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做。

项目主页:https://github.com/OpenFeign/feign

2、快速入门

①导入依赖

<!--feign-->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

②Feign的客户端

package com.lxs.consumer.client;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient("user-service")
public interface UserClient {
   @GetMapping("/user/{id}")
   String queryById(@PathVariable long id);
}

首先这是一个接口,Feign会通过动态代理,帮我们生成实现类。这点跟Mybatis的mapper很像@FeignClient ,声明这是一个Feign客户端,同时通过 value 属性指定服务名称。 接口中的定义方法,完全采用SpringMVC的注解,Feign会根据注解帮我们生成URL,并访问获取结果@GetMapping中的/user,请不要忘记;因为Feign需要拼接可访问的地址编写新的控制器类 ConsumerFeignController ,使用UserClient访问:

package com.lxs.consumer.controller;

import com.lxs.consumer.client.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cf")
public class ConsumerFeignController {
   @Autowired
   private UserClient userClient;
   @GetMapping("/{id}")
   public User queryById(@PathVariable long id){
       return userClient.queryById(id);
  }
}

③开启Feign功能

在 ConsumerApplication 启动类上,添加注解,开启Feign功能

package com.lxs.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringCloudApplication
// 开启feign功能
@EnableFeignClients
public class ConsumerApplication {
   public static void main(String[] args) {
       SpringApplication.run(ConsumerApplication.class, args);
  }
   @Bean
   @LoadBalanced
   public RestTemplate restTemplate(){
       return new RestTemplate();
  }
}

Feign中已经自动集成了Ribbon负载均衡,因此不需要自己定义RestTemplate进行负载均衡的配置。

④启动测试

访问接口:http://localhost:8080/cf/2

image-20210928101112130

正常获取到了结果。

3、负载均衡

Feign中本身已经集成了Ribbon依赖和自动配置:

image-20210928101500182

因此不需要额外引入依赖,也不需要再注册 RestTemplate 对象。

当停止userService服务,访问接口:http://localhost:8080/cf/2,发现超时时间为2s

image-20210928101657580

Fegin内置的ribbon默认设置了请求超时时长,默认是1000,我们可以通过手动配置来修改这个超时时长:

#设置feign的Ribbon
ribbon:
ReadTimeout: 2000 # 读取超时时长
ConnectTimeout: 1000 # 建立链接的超时时长

或者为某一个具体service指定

user-service:
ribbon:
  ReadTimeout: 2000 # 读取超时时长
  ConnectTimeout: 1000 # 建立链接的超时时长

在user-service中增加睡眠时间2s测试

因为ribbon内部有重试机制,一旦超时,会自动重新发起请求。如果不希望重试,可以添加配置:

修改 consumer-demo\src\main\resources\application.yml 添加如下配置 :

ribbon:
ConnectTimeout: 1000 # 连接超时时长
ReadTimeout: 2000 # 数据通信超时时长
MaxAutoRetries: 0 # 当前服务器的重试次数
MaxAutoRetriesNextServer: 0 # 重试多少次服务
OkToRetryOnAllOperations: false # 是否对所有的请求方式都重试

当再次访问接口:http://localhost:8080/cf/2,发现超时时间为1s

image-20210928102339230

4、Hystrix支持

Feign默认也有对Hystrix的集成:

image-20210928102755488

只不过,默认情况下是关闭的。需要通过下面的参数来开启:

①修改 consumer-demo\src\main\resources\application.yml 添加如下配置:

feign:
hystrix:
  enabled: true # 开启Feign的熔断功能

但是,Feign中的Fallback配置不像Ribbon中那样简单了。 Ⅰ 首先,要定义一个类,实现刚才编写的UserFeignClient,作为fallback的处理类

package com.lxs.consumer.client;

import com.lxs.consumer.pojo.User;
import org.springframework.stereotype.Component;

@Component
public class UserFeignClient implements UserClient{
   @Override
   public User queryById(long id) {
       User user = new User();
       user.setId(id);
       user.setName("用户异常");
       return user;
  }
}

Ⅱ 然后在UserClient中,指定刚才编写的实现类

package com.lxs.consumer.client;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "user-service",fallback = UserFeignClient.class)
public interface UserClient {
   @GetMapping("/user/{id}")
   User queryById(@PathVariable long id);
}

Ⅲ 重启测试

重启启动 consumer-demo 并关闭 user-service 服务,然后在页面访问:http://localhost:8080/cf/7

image-20210928103520058

5、请求压缩(了解)

Spring Cloud Feign 支持对请求和响应进行GZIP压缩,以减少通信过程中的性能损耗。通过下面的参数即可开启请 求与响应的压缩功能:

feign:
compression:
  request:
    enabled: true # 开启请求压缩
  response:
    enabled: true # 开启响应压缩

同时,我们也可以对请求的数据类型,以及触发压缩的大小下限进行设置:

feign:
compression:
  request:
    enabled: true # 开启请求压缩
    mime-types: text/html,application/xml,application/json # 设置压缩的数据类型
    min-request-size: 2048 # 设置触发压缩的大小下限
  response:
    enabled: true # 开启响应压缩

注:上面的数据类型、压缩大小下限均为默认值。

6、日志级别(了解)

前面讲过,通过 logging.level.lxs.xx=debug 来设置日志级别。然而这个对Fegin客户端而言不会产生效果。因为 @FeignClient 注解修改的客户端在被代理时,都会创建一个新的Fegin.Logger实例。我们需要额外指定这个日志的 级别才可以。

①在 consumer-demo 的配置文件中设置com.lxs包下的日志级别都为 debug 修改 consumerdemo\src\main\resources\application.yml 添加如下配置:

logging:
level:
  com.lxs: debug

②编写配置类,定义日志级别

package com.lxs.consumer.config;

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {
   //记录所有请求和响应的明细,包括头信息、请求体、元数据
   @Bean
   Logger.Level feignLoggerLevel(){
       return Logger.Level.FULL;
  }
}

这里指定的Level级别是FULL,Feign支持4种级别: NONE:不记录任何日志信息,这是默认值。 BASIC:仅记录请求的方法,URL以及响应状态码和执行时间 HEADERS:在BASIC的基础上,额外记录了请求和响应的头信息 FULL:记录所有请求和响应的明细,包括头信息、请求体、元数据。

③在 consumer-demo 的 UserClient 接口类上的@FeignClient注解中指定配置类:

别忘了去掉user-service的休眠时间

package com.lxs.consumer.client;

import com.lxs.consumer.config.FeignConfig;
import com.lxs.consumer.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "user-service",fallback = UserFeignClient.class,configuration = FeignConfig.class)
public interface UserClient {
   @GetMapping("/user/{id}")
   User queryById(@PathVariable long id);
}

④重启项目,即可看到每次访问的日志:

image-20210928104922724

十、Spring Cloud Gateway网关

1、简介

Spring Cloud Gateway是Spring官网基于Spring 5.0、 Spring Boot 2.0、Project Reactor等技术开发的网关服务。 Spring Cloud Gateway基于Filter链提供网关基本功能:安全、监控/埋点、限流等。 Spring Cloud Gateway为微服务架构提供简单、有效且统一的API路由管理方式。 Spring Cloud Gateway是替代Netflix Zuul的一套解决方案。

Spring Cloud Gateway组件的核心是一系列的过滤器,通过这些过滤器可以将客户端发送的请求转发(路由)到对应的微服务。 Spring Cloud Gateway是加在整个微服务最前沿的防火墙和代理器,隐藏微服务结点IP端口信息,从而加强安全保护。Spring Cloud Gateway本身也是一个微服务,需要注册到Eureka服务注册中心。 网关的核心功能是:过滤和路由

2、Gateway加入后的架构

image-20210928105518152

不管是来自于客户端(PC或移动端)的请求,还是服务内部调用。一切对服务的请求都可经过网关,然后再 由网关来实现 鉴权、动态路由等等操作。Gateway就是我们服务的统一入口。

3、核心概念

路由(route) 路由信息的组成:由一个ID、一个目的URL、一组断言工厂、一组Filter组成。如果路由断言为真,说明请求URL和配置路由匹配。 断言(Predicate) Spring Cloud Gateway中的断言函数输入类型是Spring 5.0框架中的ServerWebExchange。Spring Cloud Gateway的断言函数允许开发者去定义匹配来自于HTTP Request中的任何信息比如请求头和参数。 过滤器(Filter) 一个标准的Spring WebFilter。 Spring Cloud Gateway中的Filter分为两种类型的Filter,分别是Gateway Filter和Global Filter。过滤器Filter将会对请求和响应进行修改处理.

4、快速入门

需求:通过网关系统lxs-gateway将包含有 /user 的请求 路由到 http://127.0.0.1:9091/user/用户id

①新建工程

image-20210928110557355

打开 lxs-springcloud\lxs-gateway\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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <parent>
       <artifactId>lxs-springcloud</artifactId>
       <groupId>com.lxs</groupId>
       <version>1.0-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>

   <artifactId>lxs-gateway</artifactId>

   <properties>
       <maven.compiler.source>8</maven.compiler.source>
       <maven.compiler.target>8</maven.compiler.target>
   </properties>

   <dependencies>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-gateway</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
       </dependency>
   </dependencies>
</project>

②编写启动类

在lxs-gateway中创建 com.lxs.gateway.GatewayApplication 启动类

package com.lxs.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
//开启eureka的注册发现功能
@EnableDiscoveryClient
public class GatewayApplication {
   public static void main(String[] args) {
       SpringApplication.run(GatewayApplication.class, args);
  }
}

③编写配置

创建 lxs-gateway\src\main\resources\application.yml 文件,内容如下:

server:
port: 10010
spring:
application:
  name: api-gateway
eureka:
client:
  service-url:
    defaultZone: HTTP://127.0.0.1:10086/eureka
instance:
  prefer-ip-address: true

需要用网关来代理 user-service 服务,先看一下控制面板中的服务状态 :

image-20210928113416178

ip为:127.0.0.1 端口为:9092

修改 lxs-gateway\src\main\resources\application.yml 文件为:

server:
port: 10010
spring:
application:
  name: api-gateway
cloud:
  gateway:
    routes:
       #路由的id,可以随意些
      - id: user-service-rote
         #代理的微服务地址
        uri: http://127.0.0.1:9092
         #路由断言:可以配置映射路径
        predicates:
          - Path=/user/**
eureka:
client:
  service-url:
    defaultZone: http://127.0.0.1:10086/eureka
instance:
  prefer-ip-address: true

将符合 Path 规则的一切请求,都代理到 uri 参数指定的地址 本例中,我们将路径中包含有 /user/** 开头的请求, 代理到http://127.0.0.1:9092

⑤启动测试

访问的路径中需要加上配置规则的映射路径,我们访问:http://localhost:10010/user/7

image-20210928113431750

http://localhost:10010/user/7 -> http://localhost:9092/user/7

5、面向服务的路由

在刚才的路由规则中,把路径对应的服务地址写死了!如果同一服务有多个实例的话,这样做显然不合理。 应该根 据服务的名称,去Eureka注册中心查找 服务对应的所有实例列表,然后进行动态路由!

①修改映射配置,通过服务名称获取

修改 lxs-gateway\src\main\resources\application.yml 文件如下:

server:
port: 10010
spring:
application:
  name: api-gateway
cloud:
  gateway:
    routes:
       #路由的id,可以随意些
      - id: user-service-rote
         #代理的微服务地址
#         uri: http://127.0.0.1:9092
        uri: lb://user-service
         # 路由断言,可以配置映射路径
        predicates:
          - Path=/user/**
eureka:
client:
  service-url:
    defaultZone: http://127.0.0.1:10086/eureka
instance:
  prefer-ip-address: true

路由配置中uri所用的协议为lb时(以uri: lb://user-service为例),gateway将使用 LoadBalancerClient把 user-service通过eureka解析为实际的主机和端口,并进行ribbon负载均衡。

②启动测试

再次启动 lxs-gateway ,这次gateway进行代理时,会利用Ribbon进行负载均衡访问: http://localhost:10010/user/8 日志中可以看到使用了负载均衡器:

image-20210928151035080

6、路由前缀

客户端的请求地址与微服务的服务地址如果不一致的时候,可以通过配置路径过滤器实现路径前缀的添加和 去除。

提供服务的地址:http://127.0.0.1:9091/user/8 添加前缀:对请求地址添加前缀路径之后再作为代理的服务地址; http://127.0.0.1:10010/8 --> http://127.0.0.1:9091/user/8 添加前缀路径/user 去除前缀:将请求地址中路径去除一些前缀路径之后再作为代理的服务地址;

http://127.0.0.1:10010/api/user/8 --> http://127.0.0.1:9091/user/8 去除前缀路径/api

①添加前缀

在gateway中可以通过配置路由的过滤器PrefixPath,实现映射路径中地址的添加;

修改 lxs-gateway\src\main\resources\application.yml 文件:

server:
port: 10010
spring:
application:
  name: api-gateway
cloud:
  gateway:
    routes:
       #路由的id,可以随意些
      - id: user-service-rote
         #代理的微服务地址
#         uri: http://127.0.0.1:9092
        uri: lb://user-service
         # 路由断言,可以配置映射路径
        predicates:
          - Path=/**
        filters:
           # 添加请求路径的前缀
          - PrefixPath=/user
eureka:
client:
  service-url:
    defaultZone: http://127.0.0.1:10086/eureka
instance:
  prefer-ip-address: true

image-20210928151949714

通过 PrefixPath=/xxx 来指定了路由要添加的前缀。 也就是:

PrefixPath=/user http://localhost:10010/8 --》http://localhost:9091/user/8

PrefixPath=/user/abc http://localhost:10010/8 --》http://localhost:9091/user/abc/8

②去除前缀

在gateway中可以通过配置路由的过滤器StripPrefix,实现映射路径中地址的去除; 修改 lxs-gateway\src\main\resources\application.yml 文件:

server:
port: 10010
spring:
application:
  name: api-gateway
cloud:
  gateway:
    routes:
       #路由的id,可以随意些
      - id: user-service-rote
         #代理的微服务地址
#         uri: http://127.0.0.1:9092
        uri: lb://user-service
         # 路由断言,可以配置映射路径
        predicates:
          - Path=/api/user/**
        filters:
           # 表示过滤1个路径,2表示两个路径,以此类推
          - StripPrefix=1

eureka:
client:
  service-url:
    defaultZone: http://127.0.0.1:10086/eureka
instance:
  prefer-ip-address: true

通过 StripPrefix=1 来指定了路由要去掉的前缀个数。如:路径 /api/user/1 将会被代理到 /user/1 。 也就是: StripPrefix=1 http://localhost:10010/api/user/8 --》http://localhost:9091/user/8 StripPrefix=2 http://localhost:10010/api/user/8 --》http://localhost:9091/8 以此类推

image-20210928152128159

7、过滤器

①简介

Gateway作为网关的其中一个重要功能,就是实现请求的鉴权。而这个动作往往是通过网关提供的过滤器来实现 的。前面的 路由前缀 章节中的功能也是使用过滤器实现的。

Gateway自带过滤器有几十个,常见自带过滤器有:

image-20210928153236129

image-20210928153257435

详细的说明参考官网链接

配置全局默认过滤器

这些自带的过滤器可以和使用 路由前缀 章节中的用法类似,也可以将这些过滤器配置成不只是针对某个路由;而 是可以对所有路由生效,也就是配置默认过滤器:

server:
port: 10010
spring:
application:
  name: api-gateway
cloud:
  gateway:
    routes:
       #路由的id,可以随意些
      - id: user-service-rote
         #代理的微服务地址
#         uri: http://127.0.0.1:9092
        uri: lb://user-service
         # 路由断言,可以配置映射路径
        predicates:
          - Path=/api/user/**
        filters:
           # 表示过滤1个路径,2表示两个路径,以此类推
          - StripPrefix=1
     # 默认过滤器,对所有路由都生效
    default-filters:
      - AddResponseHeader=X-Response-Foo, Bar
      - AddResponseHeader=abc-myname,lxs

eureka:
client:
  service-url:
    defaultZone: http://127.0.0.1:10086/eureka
instance:
  prefer-ip-address: true

上述配置后,再访问 http://localhost:10010/api/user/7 的话;那么可以从其响应中查看到如下信息:

image-20210928153629199

过滤器类型:Gateway实现方式上,有两种过滤器;

局部过滤器:通过 spring.cloud.gateway.routes.filters 配置在具体路由下,只作用在当前路由上; 如果配置spring.cloud.gateway.default-filters 上会对所有路由生效也算是全局的过滤器;但是这些过滤器 的实现上都是要实现GatewayFilterFactory接口。 全局过滤器:不需要在配置文件中配置,作用在所有的路由上;实现 GlobalFilter 接口即可。

②执行生命周期

Spring Cloud Gateway 的 Filter 的生命周期也类似Spring MVC的拦截器有两个:“pre” 和 “post”。“pre”和 “post” 分别会在请求被执行前调用和被执行后调用

image-20210928153751058

这里的 pre 和 post 可以通过过滤器的 GatewayFilterChain 执行filter方法前后来实现

③使用场景

常见的应用场景如下:

请求鉴权:一般 GatewayFilterChain 执行filter方法前,如果发现没有访问权限,直接就返回空。 异常处理:一般 GatewayFilterChain 执行filter方法后,记录异常并返回。 服务调用时长统计: GatewayFilterChain 执行filter方法前后根据时间统计。

8、自定义过滤器

① 自定义局部过滤器

需求: 在过滤器(MyParamGatewayFilterFactory)中将http://localhost:10010/api/user/8?name=lxs中的参数name的值获取到并输出到控制台;并且参数名是可变的,也就是不一定每次都是name;需要可以通过配置过滤器的时候做到配置参数名。 在application.yml中对某个路由配置过滤器,该过滤器可以在控制台输出配置文件中指定名称的请求参数的 值。

Ⅰ 编写过滤器

package com.lxs.gateway.filter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.http.server.reactive.ServerHttpRequest;
import java.util.Arrays;
import java.util.List;
@Component
public class MyParamGatewayFilterFactory extends
       AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {
   static final String PARAM_NAME = "param";
   public MyParamGatewayFilterFactory() {
       super(Config.class);
  }
   public List<String> shortcutFieldOrder() {
       return Arrays.asList(PARAM_NAME);
  }
   @Override
   public GatewayFilter apply(Config config) {
       return (exchange, chain) -> {
           // http://localhost:10010/api/user/8?name=lxs config.param ==> name
           //获取请求参数中param对应的参数名 的参数值
           ServerHttpRequest request = exchange.getRequest();
           if(request.getQueryParams().containsKey(config.param)){
               request.getQueryParams().get(config.param).forEach(value -> System.out.printf("------------局部过滤器--------%s = %s- -----", config.param, value));
          }
           return chain.filter(exchange);
      };
  }
   public static class Config{
       //对应在配置过滤器的时候指定的参数名
       private String param;
       public String getParam() {
           return param;
      }
       public void setParam(String param) {
           this.param = param;
      }
  }
}

Ⅱ修改配置文件

server:
port: 10010
spring:
application:
  name: api-gateway
cloud:
  gateway:
    routes:
       #路由的id,可以随意些
      - id: user-service-rote
         #代理的微服务地址
#         uri: http://127.0.0.1:9092
        uri: lb://user-service
         # 路由断言,可以配置映射路径
        predicates:
          - Path=/api/user/**
        filters:
           # 表示过滤1个路径,2表示两个路径,以此类推
          - StripPrefix=1
           # 自定义过滤器
          - MyParam=name
     # 默认过滤器,对所有路由都生效
    default-filters:
      - AddResponseHeader=X-Response-Foo, Bar
      - AddResponseHeader=abc-myname,lxs

eureka:
client:
  service-url:
    defaultZone: http://127.0.0.1:10086/eureka
instance:
  prefer-ip-address: true

注意:自定义过滤器的命名应该为:***GatewayFilterFactory

测试访问:http://localhost:10010/api/user/7?name=lxs检查后台是否输出name和lxs;

但是若访问 http://localhost:10010/api/user/7?name2=kaikeba 则是不会输出的

②自定义全局过滤器

需求:编写全局过滤器,在过滤器中检查请求中是否携带token请求头。如果token请求头存在则放行;如果token为空或者不存在则设置返回的状态码为:未授权也不再执行下去。 在lxs-gateway工程编写全局过滤器类MyGlobalFilter

package com.lxs.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
   @Override
   public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       System.out.println("--------------全局过滤器MyGlobalFilter------------------");
       String token = exchange.getRequest().getHeaders().getFirst("token");
       if(StringUtils.isBlank(token)){
           //设置响应状态码为未授权
           exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
           return exchange.getResponse().setComplete();
      }
       return chain.filter(exchange);
  }
   @Override
   public int getOrder() {
       //值越小越先执行
       return 1;
  }
}

访问 http://localhost:10010/api/user/7

image-20210928162644428

访问 http://localhost:10010/api/user/7?token=abc

image-20210928162702599

9、负载均衡和熔断(了解)

Gateway中默认就已经集成了Ribbon负载均衡和Hystrix熔断机制。但是所有的超时策略都是走的默认值,比如熔 断超时时间只有1S,很容易就触发了。因此建议手动进行配置:

hystrix:
command:
  default:
    execution:
      isolation:
        thread:
          timeoutInMilliseconds: 6000 #服务降级超时时间,默认1S
ribbon:
ConnectTimeout: 1000 # 连接超时时长
ReadTimeout: 2000 # 数据通信超时时长
MaxAutoRetries: 0 # 当前服务器的重试次数
MaxAutoRetriesNextServer: 0 # 重试多少次服务

10、Gateway跨域配置

一般网关都是所有微服务的统一入口,必然在被调用的时候会出现跨域问题。 跨域:在js请求访问中,如果访问的地址与当前服务器的域名、ip或者端口号不一致则称为跨域请求。若不解决则不能获取到对应地址的返回结果。 如:从在http://localhost:9090中的js访问 http://localhost:9000的数据,因为端口不同,所以也是跨域请求。 在访问Spring Cloud Gateway网关服务器的时候,出现跨域问题的话;可以在网关服务器中通过配置解决,允许哪些服务是可以跨域请求的;具体配置如下:

server:
port: 10010
spring:
application:
  name: api-gateway
cloud:
  gateway:
    routes:
       #路由的id,可以随意些
      - id: user-service-rote
         #代理的微服务地址
#         uri: http://127.0.0.1:9092
        uri: lb://user-service
         # 路由断言,可以配置映射路径
        predicates:
          - Path=/api/user/**
        filters:
           # 表示过滤1个路径,2表示两个路径,以此类推
          - StripPrefix=1
           # 自定义过滤器
          - MyParam=name
     # 默认过滤器,对所有路由都生效
    default-filters:
      - AddResponseHeader=X-Response-Foo, Bar
      - AddResponseHeader=abc-myname,lxs
     #跨域配置
    globalcors:
      corsConfigurations:
        '[/**]':
           #allowedOrigins: * # 这种写法或者下面的都可以,*表示全部
          allowedOrigins:
            - "http://docs.spring.io"
          allowedMethods:
            - GET
#负载均衡和熔断
hystrix:
command:
  default:
    execution:
      isolation:
        thread:
          timeoutInMilliseconds: 6000 #服务降级超时时间,默认1S
ribbon:
ConnectTimeout: 1000 # 连接超时时长
ReadTimeout: 2000 # 数据通信超时时长
MaxAutoRetries: 0 # 当前服务器的重试次数
MaxAutoRetriesNextServer: 0 # 重试多少次服务

eureka:
client:
  service-url:
    defaultZone: http://127.0.0.1:10086/eureka
instance:
  prefer-ip-address: true

说明: 上述配置表示:可以允许来自 http://docs.spring.io 的get请求方式获取服务数据。 allowedOrigins 指定允许访问的服务器地址,如:http://localhost:10000 也是可以的。 '[/**]' 表示对所有访问到网关服务器的请求地址 官网具体说明:https://cloud.spring.io/spring-cloud-static/spring-cloudgateway/2.1.1.RELEASE/multi/multi__cors_configuration.html

11、Gateway的高可用(了解)

启动多个Gateway服务,自动注册到Eureka,形成集群。如果是服务内部访问,访问Gateway,自动负载均衡,没问题。 但是,Gateway更多是外部访问,PC端、移动端等。它们无法通过Eureka进行负载均衡,那么该怎么办? 此时,可以使用其它的服务网关,来对Gateway进行代理。比如:Nginx

12、Gateway与Feign的区别

Gateway 作为整个应用的流量入口,接收所有的请求,如PC、移动端等,并且将不同的请求转- 发至不同的处理微服务模块,其作用可视为nginx;大部分情况下用作权限鉴定、服务端流量控制 Feign 则是将当前微服务的部分服务接口暴露出来,并且主要用于各个微服务之间的服务调用

十一、Spring Cloud Config分布式配置中心

1、简介

在分布式系统中,由于服务数量非常多,配置文件分散在不同的微服务项目中,管理不方便。为了方便配置文件集中管理,需要分布式配置中心组件。在Spring Cloud中,提供了Spring Cloud Config,它支持配置文件放在配置服务的本地,也支持放在远程Git仓库(GitHub、码云)。 使用Spring Cloud Config配置中心后的架构如下图

image-20210928164838562

配置中心本质上也是一个微服务,同样需要注册到Eureka服务注册中心!

2、Git配置管理

知名的Git远程仓库有国外的GitHub和国内的码云(gitee);但是使用GitHub时,国内的用户经常遇到的问题是访问速度太慢,有时候还会出现无法连接的情况。如果希望体验更好一些,可以使用国内的Git托管服务——码云(gitee.com)。 与GitHub相比,码云也提供免费的Git仓库。此外,还集成了代码质量检测、项目演示等功能。 对于团队协作开发,码云还提供了项目管理、代码托管、文档管理的服务。本章中使用的远程Git仓库是码云。 码云访问地址:https://gitee.com/

①创建远程仓库

首先要使用码云上的私有远程git仓库需要先注册帐号;请先自行访问网站并注册帐号,然后使用帐号登录码云控制 台并创建公开仓库。

image-20210928164931724

image-20210928164947240

②创建配置文件

在新建的仓库中创建需要被统一配置管理的配置文件。 配置文件的命名方式:{application}-{profile}.yml 或 {application}-{profile}.properties application为应用名称 profile用于区分开发环境,测试环境、生产环境等 如user-dev.yml,表示用户微服务开发环境下使用的配置文件。 这里将user-service工程的配置文件application.yml文件的内容复制作为user-dev.yml文件的内容,具体配置如下:

image-20210928165141536

创建完user-dev.yml配置文件之后,gitee中的仓库如下:

image-20210928165240075

3、搭建配置中心微服务

①创建项目

创建配置中心微服务工程:

image-20210928165313207

添加依赖,修改 config-server\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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <parent>
       <artifactId>lxs-springcloud</artifactId>
       <groupId>com.lxs</groupId>
       <version>1.0-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>

   <artifactId>config-server</artifactId>

   <properties>
       <maven.compiler.source>8</maven.compiler.source>
       <maven.compiler.target>8</maven.compiler.target>
   </properties>

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

</project>

②启动类

创建配置中心工程 config-server 的启动类; config-server\src\main\java\com\lxs\config\ConfigServerApplication.java 如下:

package com.lxs.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer //开启配置服务
public class ConfigServerApplication {
   public static void main(String[] args) {
       SpringApplication.run(ConfigServerApplication.class, args);
  }
}

③配置文件

server:
port: 12000
spring:
application:
  name: config-server
cloud:
  config:
    server:
      git:
        uri: https://gitee.com/ma-shikai/my-config.git
eureka:
client:
  service-url:
    defaultZone: http://127.0.0.1:10086/eureka

注意上述的 spring.cloud.config.server.git.uri 则是在码云创建的仓库地址;可修改为你自己创建的仓库地址

④启动测试

启动eureka注册中心和配置中心;然后访问http://localhost:12000/user-dev.yml ,查看能否输出在码云存储管理 的user-dev.yml文件。并且可以在gitee上修改user-dev.yml然后刷新上述测试地址也能及时到最新数据。

image-20210928165810927

4、获取配置中心配置

前面已经完成了配置中心微服务的搭建,下面我们就需要改造一下用户微服务 user-service ,配置文件信息不再由微服务项目提供,而是从配置中心获取。如下对 user-service 工程进行改造。

①添加依赖

在 user-service 工程中的pom.xml文件中添加如下依赖:

<!--获取配置中心配置依赖-->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

②修改配置

Ⅰ 删除 user-service 工程的 user-service\src\main\resources\application.yml 文件(因为该文件从配置中心获取)

Ⅱ 创建 user-service 工程 user-service\src\main\resources\bootstrap.yml 配置文件

spring:
cloud:
  config:
     # 要与仓库中的配置文件的application保持一致
    name: user
     # 要与仓库中的配置文件的profile保持一致
    profile: dev
     # 要与仓库中的配置文件所属的版本(分支)一样
    label: master
    discovery:
       # 使用配置中心
      enabled: true
       # 配置中心服务名
      service-id: config-server
eureka:
client:
  service-url:
    defaultZone: http://127.0.0.1:10086/eureka

user-service 工程修改后结构:

image-20210928170718988

bootstrap.yml文件也是Spring Boot的默认配置文件,而且其加载的时间相比于application.yml更早。 application.yml和bootstrap.yml虽然都是Spring Boot的默认配置文件,但是定位却不相同。bootstrap.yml可以理解成系统级别的一些参数配置,这些参数一般是不会变动的。application.yml 可以用来定义应用级别的参数,如果搭配 spring cloud config 使用,application.yml 里面定义的文件可以实现动态替换。 总结就是,bootstrap.yml文件相当于项目启动时的引导文件,内容相对固定。application.yml文件是微服务的一些常规配置参数,变化比较频繁。

③启动测试

启动注册中心 eureka-server 、配置中心 config-server 、用户服务 user-service ,如果启动没有报错其实已经 使 用上配置中心内容,可以到注册中心查看,也可以检验 user-service 的服务。

image-20210928170914783

十二、Spring Cloud Bus服务总线

1、问题

前面已经完成了将微服务中的配置文件集中存储在远程Git仓库,并且通过配置中心微服务从Git仓库拉取配置文 件, 当用户微服务启动时会连接配置中心获取配置信息从而启动用户微服务。 如果我们更新Git仓库中的配置文 件,那用户微服务是否可以及时接收到新的配置信息并更新呢

①修改远程Git配置

修改在码云上的user-dev.yml文件,添加一个属性test.name 。

image-20210928174632198

②修改UserController

修改 user-service 工程中的处理器类; user-service\src\main\java\com\lxs\user\controller\UserController.java 如下:

package com.lxs.user.controller;

import com.lxs.user.pojo.User;
import com.lxs.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
//开启Eureka客户端发现功能
@EnableEurekaClient
public class UserController {
   @Autowired
   private UserService userService;
   @Value("${test.name}")
   private String name;
   @RequestMapping("/{id}")
   public User queryById(@PathVariable Long id) {
       System.out.println("配置文件中的test.name为:" + name);
       return userService.queryById(id);
  }
}

③测试

依次启动注册中心 eureka-server 、配置中心 config-server 、用户服务 user-service ;然后修改Git仓库中的配置信息,访问用户微服务,查看输出内容。 结论:通过查看用户微服务控制台的输出结果可以发现,我们对于Git仓库中配置文件的修改并没有及时更新到用户微服务,只有重启用户微服务才能生效。 如果想在不重启微服务的情况下更新配置该如何实现呢? 可以使用Spring Cloud Bus来实现配置的自动更新。

需要注意的是Spring Cloud Bus底层是基于RabbitMQ实现的,默认使用本地的消息队列服务,所以需要提前启动本地RabbitMQ服务(安装RabbitMQ以后才有),如下:

先安装otp_win64_23.0.exe,再安装rabbitmq-server-3.8.5.exe

重启UserApplication,查看控制台是否输出lxs

2、Spring Cloud Bus简介

Spring Cloud Bus是用轻量的消息代理将分布式的节点连接起来,可以用于广播配置文件的更改或者服务的监控管 理。也就是消息总线可以为微服务做监控,也可以实现应用程序之间相互通信。 Spring Cloud Bus可选的消息代理 有RabbitMQ和Kafka。

使用了Bus之后 :

image-20210928180050467

准备工作 安装资料中\otp_win64_23.0.exe和rabbitmq-server-3.8.5.exe

3、改造配置中心

在 config-server 项目的pom.xml文件中加入Spring Cloud Bus相关依赖

<!--Spring Cloud Bus相关依赖-->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-bus</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>

在 config-server 项目修改application.yml文件如下:

server:
port: 12000
spring:
application:
  name: config-server
cloud:
  config:
    server:
      git:
        uri: https://gitee.com/ma-shikai/my-config.git
 # 配置rabbitmq信息;如果是都与默认值一致则不需要配置
rabbitmq:
  host: localhost
  port: 5672
  username: guest
  password: guest
eureka:
client:
  service-url:
    defaultZone: http://127.0.0.1:10086/eureka
management:
endpoints:
  web:
    exposure:
       # 暴露触发消息总线的地址
      include: bus-refresh

4、改造用户服务

①在用户微服务 user-service 项目的pom.xml中加入Spring Cloud Bus相关依赖

<!--Spring Cloud Bus相关依赖-->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-bus</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

②修改 user-service 项目的bootstrap.yml如下

spring:
cloud:
  config:
     # 要与仓库中的配置文件的application保持一致
    name: user
     # 要与仓库中的配置文件的profile保持一致
    profile: dev
     # 要与仓库中的配置文件所属的版本(分支)一样
    label: master
    discovery:
       # 使用配置中心
      enabled: true
       # 配置中心服务名
      service-id: config-server
 # 配置rabbitmq信息;如果是都与默认值一致则不需要配置
rabbitmq:
  host: localhost
  port: 5672
  username: guest
  password: guest
eureka:
client:
  service-url:
    defaultZone: http://127.0.0.1:10086/eureka

③改造用户微服务 user-service 项目的UserController

package com.lxs.user.controller;

import com.lxs.user.pojo.User;
import com.lxs.user.service.UserService;
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.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
//刷新配置
@RefreshScope
//开启Eureka客户端发现功能
@EnableEurekaClient
public class UserController {
   @Autowired
   private UserService userService;
   @Value("${test.name}")
   private String name;
   @RequestMapping("/{id}")
   public User queryById(@PathVariable Long id) {
       System.out.println("配置文件中的test.name为:" + name);
       return userService.queryById(id);
  }
}

5、测试

前面已经完成了配置中心微服务和用户微服务的改造,下面来测试一下,当我们修改了Git仓库中的配置文件,用户微服务是否能够在不重启的情况下自动更新配置信息。 测试步骤: 第一步:依次启动注册中心 eureka-server 、配置中心 config-server 、用户服务 user-service 第二步:访问用户微服务http://localhost:9091/user/7;查看IDEA控制台输出结果 第三步:修改Git仓库中配置文件 user-dev.yml 的 test.name 内容 第四步:使用Postman或者RESTClient工具发送POST方式请求访问地址 http://127.0.0.1:12000/actuator/bus-refresh

image-20210928180801864

第五步:访问用户微服务系统控制台查看输出结果

说明:

  1. Postman或者RESTClient是一个可以模拟浏览器发送各种请求(POST、GET、PUT、DELETE等)的工具

  2. 请求地址http://127.0.0.1:12000/actuator/bus-refresh中 /actuator是固定的

  3. 请求http://127.0.0.1:12000/actuator/bus-refresh地址的作用是访问配置中心的消息总线服务,消息总线服务接收到请求后会向消息队列中发送消息,各个微服务会监听消息队列。当微服务接收到队列中的消息后,会重新从配置中心获取最新的配置信息

6、Spring Cloud 完整体系架构图

image-20210928181249144

 

posted @ 2021-10-02 16:25  马世凯  阅读(59)  评论(0)    收藏  举报