0
点赞
收藏
分享

微信扫一扫

12-微服务与分布式_Spring Cloud(下)


目录

​​六,feign​​

​​1,简介​​

​​2,简单案例​​

​​3,feign-ribbon负载均衡​​

​​4,服务降级​​

​​5,请求压缩​​

​​6,日志打印​​

​​七,gateway​​

​​1,简介​​

​​2,入门案例​​

​​3,面向服务的路由​​

​​4,路径前缀处理​​

​​5,过滤器​​

​​5.1 简介​​

​​5.2 配置全局默认过滤器​​

​​5.3 执行生命周期​​

​​5.4 自定义局部过滤器​​

​​5.5 自定义全局过滤器​​

​​6,其他配置​​

​​6.1 负载均衡和熔断(了解)​​

​​6.2 Gateway跨域配置​​

​​6.3 Gateway高可用(了解)​​

​​6.4 Gateway与Feign的区别​​

​​八,config​​

​​1,搭建配置中心​​

​​2,使用配置中心配置​​

​​2.1 配置中心微服务的搭建​​

​​2.2 改造用户微服务 user-service​​

​​九,bus​​

​​1,问题​​

​​2,简介​​

​​3,应用​​

​​十,体系架构图​​

六,feign

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

String baseUrl = "http://user-service/user/"; 
User user = this.restTemplate.getForObject(baseUrl + id, User.class)

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

1,简介

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

项目主页:​​GitHub - OpenFeign/feign: Feign makes writing java http clients easier​​

2,简单案例

1,导入依赖

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

2,创建Feign的客户端

@FeignClient("user-service")
public interface UserClient {

//http://user-service/user/123
@GetMapping("/user/{id}")
User queryById(@PathVariable("id") Long id);

}

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

3,编写新的控制器类 ConsumerFeignController ,使用UserClient访问

@RestController
@RequestMapping("/cf")
public class ConsumerFeignController {

@Autowired
private UserClient userClient;

@GetMapping("/{id}")
public User queryById(@PathVariable Long id){
return userClient.queryById(id);
}
}

4,开启Feign功能

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

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

// Feign中已经自动集成了Ribbon负载均衡,因此不需要自己定义RestTemplate进行负载均衡的配置。
// 下面的代码可以注释掉
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

5,测试

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

3,feign-ribbon负载均衡

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

12-微服务与分布式_Spring Cloud(下)_负载均衡

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

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

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

# 或者为某一个具体service指定
user-service
ribbon:
ReadTimeout: 2000 # 读取超时时长
ConnectTimeout: 1000 # 建立链接的超时时长

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

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

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

4,服务降级

Feign默认也有对Hystrix的集成:

12-微服务与分布式_Spring Cloud(下)_spring cloud_02

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

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

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

1,首先,要定义一个类,实现刚才编写的UserFeignClient,作为fallback的处理类

package com.lxs.consumer.client.fallback;
import com.lxs.consumer.client.UserClient;
import com.lxs.consumer.pojo.User;
import org.springframework.stereotype.Component;

@Component
public class UserClientFallback implements UserClient {

@Override
public User queryById(Long id) {
User user = new User();
user.setId(id);
user.setName("用户异常");
return user;
}
}

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

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

3,重启测试

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

12-微服务与分布式_Spring Cloud(下)_java_03

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 # 设置触发压缩的大小下限

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

6,日志打印

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

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

logging: 
level:
com.xxy: debug

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

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:记录所有请求和响应的明细,包括头信息、请求体、元数据。

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

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

@FeignClient(value = "user-service", fallback = UserClientFallback.class, configuration = FeignConfig.class)

public interface UserClient {
@GetMapping("/user/{id}")
User queryById(@PathVariable("id") Long id);

}

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

12-微服务与分布式_Spring Cloud(下)_spring_04

七,gateway

1,简介

Spring Cloud Gateway组件的核心是一系列的过滤器,通过这些过滤器可以将客户端发送的请求转发(路由)到对应的微服务。

Spring Cloud Gateway是加在整个微服务最前沿的防火墙和代理器,隐藏微服务结点IP端口信息,从而加强安全保护。Spring Cloud Gateway本身也是一个微服务,需要注册到Eureka服务注册中心。

网关的核心功能是:过滤和路由

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

12-微服务与分布式_Spring Cloud(下)_微服务_05

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

路由(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将会对请求和响应进行修改处理

2,入门案例

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

1,新建工程

12-微服务与分布式_Spring Cloud(下)_java_06

2,打开 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>

<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>

2,编写启动类

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

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

3,编写配置

创建 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 服务,先看一下控制面板中的服务状态 :

12-微服务与分布式_Spring Cloud(下)_spring_07

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

server: 
port: 10010
spring:
application:
name:
api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: user-service-route
# 代理的服务地址
uri: HTTP://127.0.0.1:9091
# 路由断言,可以配置映射路径
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:9091

4,启动测试

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

12-微服务与分布式_Spring Cloud(下)_负载均衡_08

3,面向服务的路由

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

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

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

server: 
port: 10010
spring:
application:
name:
api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: user-service-route
# 代理的服务地址
# uri: HTTP://127.0.0.1:9091
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为例。lb:loadBalance),gateway将使用 LoadBalancerClient把 user-service通过eureka解析为实际的主机和端口,并进行ribbon负载均衡。

2,测试

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

12-微服务与分布式_Spring Cloud(下)_微服务_09

4,路径前缀处理

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

提供服务的地址: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;

1,添加前缀

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

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

12-微服务与分布式_Spring Cloud(下)_微服务_10

12-微服务与分布式_Spring Cloud(下)_spring cloud_11

2,去除前缀

在gateway中可以通过配置路由的过滤器StripPrefix,实现映射路径中地址的去除;

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

12-微服务与分布式_Spring Cloud(下)_spring cloud_12

通过 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

5,过滤器

5.1 简介

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

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

12-微服务与分布式_Spring Cloud(下)_spring cloud_13

12-微服务与分布式_Spring Cloud(下)_java_14

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

 

详细的说明参考 ​​Spring Cloud Gateway​​

5.2 配置全局默认过滤器

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

12-微服务与分布式_Spring Cloud(下)_spring cloud_15

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

12-微服务与分布式_Spring Cloud(下)_微服务_16

5.3 执行生命周期

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

12-微服务与分布式_Spring Cloud(下)_微服务_17


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

常见的应用场景如下: 

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

5.4 自定义局部过滤器

在过滤器(MyParamGatewayFilterFactory)中将​​http://localhost:10010/api/user/8?name=lxs​​中的参数name的值获取到并输出到控制台;并且参数名是可变的,也就是不一定每次都是name;需要可以通过配置过滤器的时候做到配置参数名。

在application.yml中对某个路由配置过滤器,该过滤器可以在控制台输出配置文件中指定名称的请求参数的值。

1,编写过滤器

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

import org.springframework.cloud.gateway.filter.GatewayFilter; 
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.HTTP.server.reactive.ServerHTTPRequest;
import org.springframework.stereotype.Component;
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;
}
}
}

12-微服务与分布式_Spring Cloud(下)_微服务_18

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

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

5.5 自定义全局过滤器

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

在lxs-gateway工程编写全局过滤器类MyGlobalFilter

@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

12-微服务与分布式_Spring Cloud(下)_spring cloud_19

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

12-微服务与分布式_Spring Cloud(下)_spring cloud_20

6,其他配置

6.1 负载均衡和熔断(了解)

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

hystrix: 
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 6000 #服务降级超时时间,默认1S

ribbon:
ConnectTimeout: 1000 # 连接超时时长
ReadTimeout: 2000 # 数据通信超时时长
MaxAutoRetries: 0 # 当前服务器的重试次数
MaxAutoRetriesNextServer: 0 # 重试多少次服务

6.2 Gateway跨域配置

一般网关都是所有微服务的统一入口,必然在被调用的时候会出现跨域问题。 

跨域:在js请求访问中,如果访问的地址与当前服务器的域名、ip或者端口号不一致则称为跨域请求。若不解决则不能获取到对应地址的返回结果。 

如:从在http://localhost:9090中的js访问 http://localhost:9000的数据,因为端口不同,所以也是跨域请求。 

在访问Spring Cloud Gateway网关服务器的时候,出现跨域问题的话;可以在网关服务器中通过配置解决,允许哪 些服务是可以跨域请求的;具体配置如下: 

12-微服务与分布式_Spring Cloud(下)_spring cloud_21

上述配置表示:可以允许来自 http://docs.spring.io 的get请求方式获取服务数据。 

allowedOrigins 指定允许访问的服务器地址,如:http://localhost:10000 也是可以的。 

'[/**]' 表示对所有访问到网关服务器的请求地址 

官网具体说明:​​10. CORS Configuration (spring.io)​​

6.3 Gateway高可用(了解)

启动多个Gateway服务,自动注册到Eureka,形成集群。如果是服务内部访问,访问Gateway,自动负载均衡,没问题。 

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

6.4 Gateway与Feign的区别

Gateway 作为整个应用的流量入口,接收所有的请求,如PC、移动端等,并且将不同的请求转- 发至不同的处理微服务模块,其作用可视为nginx;大部分情况下用作权限鉴定、服务端流量控制;  

Feign 则是将当前微服务的部分服务接口暴露出来,并且主要用于各个微服务之间的服务调用;

八,config

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

使用Spring Cloud Confifig配置中心后的架构如下图:

12-微服务与分布式_Spring Cloud(下)_微服务_22

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

1,搭建配置中心

1,创建远程仓库

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

12-微服务与分布式_Spring Cloud(下)_spring cloud_23

12-微服务与分布式_Spring Cloud(下)_java_24

2,创建配置文件

在新建的仓库中创建需要被统一配置管理的配置文件。

配置文件的命名方式:{application}-{profifile}.yml 或 {application}-{profifile}.properties

  • application为应用名称
  • profifile用于区分开发环境,测试环境、生产环境等

如user-dev.yml,表示用户微服务开发环境下使用的配置文件。

这里将user-service工程的配置文件application.yml文件的内容复制作为user-dev.yml文件的内容,具体配置如下

12-微服务与分布式_Spring Cloud(下)_java_25

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

12-微服务与分布式_Spring Cloud(下)_负载均衡_26

2,使用配置中心配置

2.1 配置中心微服务的搭建

1,创建配置中心微服务工程

12-微服务与分布式_Spring Cloud(下)_负载均衡_27

2,添加依赖,修改 config-server\pom.xml 如下

12-微服务与分布式_Spring Cloud(下)_spring_28

 3,创建配置中心工程 config-server 的启动类

12-微服务与分布式_Spring Cloud(下)_负载均衡_29

4,配置文件

12-微服务与分布式_Spring Cloud(下)_spring cloud_30

注意上述的 spring.cloud.config.server.git.uri 则是在码云创建的仓库地址;

5,启动测试

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

12-微服务与分布式_Spring Cloud(下)_负载均衡_31

2.2 改造用户微服务 user-service

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

1,在pom中添加依赖

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

2,修改配置

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

12-微服务与分布式_Spring Cloud(下)_微服务_32

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文件是微服务的一些常规配置参数,变化比较频繁。

3,启动测试

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

12-微服务与分布式_Spring Cloud(下)_java_33

九,bus

1,问题

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

1,修改git中配置文件

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

12-微服务与分布式_Spring Cloud(下)_spring_34

2,修改 user-service 工程中的处理器类;

12-微服务与分布式_Spring Cloud(下)_微服务_35

3,启动测试

依次启动注册中心 eureka-server 、配置中心 config-server 、用户服务 user-service ;然后修改Git仓库中的配 置信息,访问用户微服务,查看输出内容。

结论:通过查看用户微服务控制台的输出结果可以发现,我们对于Git仓库中配置文件的修改并没有及时更新到用 户微服务,只有重启用户微服务才能生效。

如果想在不重启微服务的情况下更新配置该如何实现呢? 可以使用Spring Cloud Bus来实现配置的自动更新。

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

2,简介

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

12-微服务与分布式_Spring Cloud(下)_spring_36

3,应用

1,改造配置中心

在 config-server 项目的pom.xml文件中加入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>

12-微服务与分布式_Spring Cloud(下)_java_37

2,改造用户服务

在用户微服务 user-service 项目的pom.xml中加入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>

12-微服务与分布式_Spring Cloud(下)_微服务_38

12-微服务与分布式_Spring Cloud(下)_负载均衡_39

3,测试

前面已经完成了配置中心微服务和用户微服务的改造,下面来测试一下,当我们修改了Git仓库中的配置文件,用 户微服务是否能够在不重启的情况下自动更新配置信息。 测试步骤:

  • 第一步:依次启动注册中心 eureka-server 、配置中心 confifig-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 
  • 第五步:访问用户微服务系统控制台查看输出结果

12-微服务与分布式_Spring Cloud(下)_spring_40

补充

  • Postman或者RESTClient是一个可以模拟浏览器发送各种请求(POST、GET、PUT、DELETE等)的工具 ;
  • 请求地址http://127.0.0.1:12000/actuator/bus-refresh中 /actuator是固定的
  • 请求http://127.0.0.1:12000/actuator/bus-refresh地址的作用是访问配置中心的消息总线服务,消息总线服务接收到请求后会向消息队列中发送消息,各个微服务会监听消息队列。当微服务接收到队列中的消息后,会重新从配置中心获取最新的配置信息 ;

十,体系架构图

12-微服务与分布式_Spring Cloud(下)_spring cloud_41

举报

相关推荐

0 条评论