Spring Cloud入门看这一篇就够了

Spring Cloud入门看这一篇就够了

SpringCloud微服务

架构演进

  • 单体架构
  • 垂直拆分
  • 分布式SOA面向服务架构
  • 微服务架构

服务调用方式

  • RPC,早期的webservice,现在热门的dubbo,都是RPC的典型代表
  • HTTP,HttpClient,OKHttp,URLConnection,RestTemplate

Euraka服务注册中心

注册中心

  • 添加依赖
  • org.springframework.cloudspring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-netflix-eureka-server

  • 使用@EnableEurekaServer注解开启注册服务
  • @SpringBootApplication@EnableEurekaServerpublic class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); }}

  • 编写配置文件application.yml
  • server: port: 8761eureka: instance: hostname: localhost client: registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ #是否将自己注册到Eureka服务中,默认为true(由于当前就是eureka服务,固设置为false) registerWithEureka: false #设置是否从eureka服务上获取注册信息,默认为true(由于当前就是eureka服务,固设置为false) fetchRegistry: false server: # 是否开启自我保护模式(自我保护模式,当eureka在一定时间内没有接受到某个微服务实例的心跳包,默认90S会注销该实例), # 一旦进入自我保护模式,若短时间内丢失大量客户端,eureka也会保护注册表的信息,不再注销 enable-self-preservation: false # 清理间隔。默认为60000ms eviction-interval-timer-in-ms: 5000

    服务提供者(服务注册)

  • 添加依赖
  • org.springframework.cloud spring-cloud-starter-netflix-eureka-client </dependency

    2.添加 @EnableDiscoveryClient 来开启Eureka客户端功能

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

    3.编写配置文件

    eureka: instance: #在调用服务的时候就已经变成ip地址;需要注意的是:不是在eureka中的控制台服务实例状态显示。 ip-address: 127.0.0.1 prefer-ip-address: true #使用ip注册 client: # 是否开启健康检查 healthcheck: enabled: true # 集群url service-url: defaultZone: http://127.0.0.1:8761/eureka

    服务消费者(服务发现)

    消费应用从注册中心获取服务列表,从而得知每个服务方的信息,知道去哪里调用服务方

    服务续约

    在注册服务完成以后,服务提供者会维持一个心跳(定时向EurekaServer发起Rest请求),有两个重要参数可以修改服务续约的行为

    eureka: instance: #服务失效时间,默认值90秒lease-expiration-duration-in-seconds: 90 #服务续约(renew)的间隔,默认为30秒lease-renewal-interval-in-seconds: 30

    也就是说,默认情况下每隔30秒服务会向注册中心发送一次心跳,证明自己还活着。如果超过90秒没有发送心跳,EurekaServer就会认为该服务宕机,会定时(eureka.server.eviction-interval-timer-in-ms设定的时间)从服务列表中剔除

    失效剔除和自我保护

    服务注册中心在启动时会创建一个定时任务,默认每隔一段时间(默认为60秒)将当前清单中超时(默认为90秒)没有续约的服务剔除。

    Eureka Server在运行期间,会统计心跳失败的比例在15分钟之内是否低于85%,如果出现低于的情况,Eureka Server会将当前的实例注册信息保护起来,不再删除服务注册表中的数据(也就是不会注销任何微服务)

    Consul

    特性

    • 高效的Raft一致性算法
    • 支持多数据中心
    • 支持健康检查
    • HTTP和DNS支持

    Consul和Eureka的区别:

    • Consul强一致性(CP),Eureka保证高可用和最终一致性(AP)
    • Consul使用Go语言,Eureka使用Java语言
    • Consul 不同于 Eureka 需要单独安装,官网:https://www.consul.io/downloads

    Consul架构图

    Consul基本使用

    服务提供者

  • pom.xml添加依赖
  • org.springframework.cloudspring-cloud-starter-consul-discovery org.springframework.bootspring-boot-starter-actuator

  • 通过@EnableDiscoveryClient注解开启对服务发现的支持
  • 编写配置文件application.yml
  • spring: application: name: consul-provider ####consul注册中心地址 cloud: consul: host: localhost port: 8500 discovery: service-name: ${spring.application.name} #注册中心名字与spring的应用名称一致 #—————————–相关配置—————————-| #是否注册 register: true #实例ID instance-id: ${spring.application.name}-1 #服务实例名称 service-name: ${spring.application.name} #服务实例端口 port: ${server.port} #健康检查路径 healthCheckPath: /actuator/health #健康检查时间间隔 healthCheckInterval: 15s #开启ip地址注册 prefer-ip-address: true #实例的请求ip ip-address: ${spring.cloud.client.ip-address}

    服务消费者

  • pom.xml添加依赖
  • org.springframework.cloudspring-cloud-starter-consul-discovery

  • 编写配置文件application.yml
  • spring: application: name: consul-provider ####consul注册中心地址 cloud: consul: host: localhost port: 8500 discovery: #设置不需要注册到Consul中 register: false

    负载均衡Ribbon

    Ribbon是 Netflix 发布的一个负载均衡器,有助于控制 HTTP 和 TCP客户端行为。Ribbon自动的从注册中心中获取服务提供者的

    列表信息,并基于内置的负载均衡算法,请求服务。

    搭建过程

  • 启动两个服务实例
  • 先编写请求的接口

    @Value(“${spring.cloud.client.ip-address}”)private String ip;@Value(“${server.port}”)private String port;@ResponseBody@RequestMapping(value = “backInfo”, method = RequestMethod.GET)public String backInfo() {return “调用的是” + ip + “端口是:” + port;}

    我们假设搭建两台服务提供者,端口分别为:8090和8091,将已有服务的配置更改为

    server: #的${}表示在jvm启动时候若能找到对应port则使用,若无则使用后面的默认值port: ${port:8090}

    另外一台在启动的时候可以指定端口port,在如下界面中的 VM options 中设置 -Dport=10087

  • 启动负载均衡
  • 因为Eureka中已经集成了Ribbon,所以我们无需引入新的依赖。直接修改消费者的启动类

    @Bean@LoadBalancedpublic RestTemplate restTemplate() {return new RestTemplate();}

  • 调取服务提供者接口,页面进行测试,可以分别请求到8090和8091两个端口
  • @Autowiredprivate RestTemplate restTemplate;@ResponseBody@RequestMapping(value = “getIpAndPort”, method = RequestMethod.GET)public String printInfo() {String url = “http://springbootdemo/backInfo”;return restTemplate.getForObject(url, String.class);}

    负载均衡策略

    Ribbon默认的负载均衡策略是轮询,Ribbon内置了多种负载均衡策略

    修改负载均衡规则的配置:

    springbootdemo: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #格式是: {服务名称}.ribbon.NFLoadBalancerRuleClassName

    • com.netflix.loadbalancer.RoundRobinRule :以轮询的方式进行负载均衡。
    • com.netflix.loadbalancer.RandomRule :随机策略
    • com.netflix.loadbalancer.RetryRule :重试策略
    • com.netflix.loadbalancer.WeightedResponseTimeRule :权重策略
    • com.netflix.loadbalancer.BestAvailableRule :最佳策略
    • com.netflix.loadbalancer.AvailabilityFilteringRule :可用过滤策略

    策略选择:

  • 如果每个机器配置一样,则建议不修改策略 (推荐)
  • 如果部分机器配置强,则可以改为 WeightedResponseTimeRule
  • 源码跟踪

    RibbonAutoConfifiguration->LoadBalancerAutoConfiguration->LoadBalancerInterceptor

    服务调用Feign

    Feign是一种声明式、模板化的HTTP客户端。

    基于Feign的服务调用

    1.在消费者引入依赖

    org.springframework.cloud spring-cloud-starter-openfeign

    2.启动类开启feign支持

    @SpringBootApplication@EnableDiscoveryClient@ComponentScan(basePackages = “com.jyd0124.consume_server.*”)@EnableFeignClientspublic class ConsumeServerApplication { public static void main(String[] args) { SpringApplication.run(ConsumeServerApplication.class, args); } @Bean @LoadBalanced public RestTemplate returnBean() { return new RestTemplate(); }}

    3.创建接口和定义需要远程调用的方法

    @FeignClient(“springbootdemo”)public interface SpringBootFeign { @RequestMapping(value = “/person”, method = RequestMethod.GET) public Map getPerson(@RequestParam(value = “id”) int id);}

    4.调用服务。

    @Autowiredprivate SpringBootFeign springBootFeign; @ResponseBody@RequestMapping(value = “/person/{id}”, method = RequestMethod.GET)public Map printInfo(@PathVariable(“id”) int id) {return springBootFeign.getPerson(id);}

    5.访问,测试结果

    负载均衡

    Feign中本身已经集成了Ribbon依赖和自动配置,因此我们不需要额外引入依赖,也不需要再注册RestTemplate 对象,可以通过 ribbon.xx 来进行全局配置。也可以通过 服务名.ribbon.xx 来对指定服务配置。

    Feign的配置

    feign: client: config: feignName: ##定义FeginClient的名称 connectTimeout: 5000 # 建立链接的超时时长 readTimeout: 5000 # 读取超时时长 # 配置Feign的日志级别,相当于代码配置方式中的Logger loggerLevel: full # Feign的错误解码器,相当于代码配置方式中的ErrorDecoder errorDecoder: com.example.SimpleErrorDecoder # 配置重试,相当于代码配置方式中的Retryer retryer: com.example.SimpleRetryer # 配置拦截器,相当于代码配置方式中的 RequestInterceptor requestInterceptors: – com.example.FooRequestInterceptor – com.example.BarRequestInterceptor #配置熔断不处理404异常 decode404: false

    请求压缩: 支持对请求和响应进行GZIP压缩,以减少通信过程中的性能损耗

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

    Hystrix支持

    Feign默认也有对Hystrix的集成

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

    日志级别

    默认情况下Feign的日志是没有开启的。

    feign: client: config: feignName: loggerLevel: full #NONE【性能最佳,适用于生产】:不记录任何日志(默认值) #BASIC【适用于生产环境追踪问题】:仅记录请求方法、URL、响应状态代码以及执行时间 #HEADERS:记录BASIC级别的基础上,记录请求和响应的header。 #FULL【比较适用于开发及测试环境定位问题】:记录请求和响应的header、body和元数据

    熔断器Hystrix

    雪崩效应

    在微服务架构中,根据业务来拆分成一个个的服务,服务与服务之间可以相互调用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign来调用。为了保证其高可用,单个服务通常会集群部署。由于网络原因或者自身的原因,服务并不能保证100%可用,如果单个服务出现问题,调用这个服务就会出现线程阻塞,此时若有大量的请求涌入,Servlet容器的线程资源会被消耗完毕,导致服务瘫痪。服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的“雪崩”效应。

    Hystrix的特性

    • 服务熔断

    Hystrix的熔断状态机模型:

    hystrix: command: default: execution.isolation.thread.timeoutInMilliseconds: 2000 circuitBreaker: errorThresholdPercentage: 50 # 触发熔断错误比例阈值,默认值50% sleepWindowInMilliseconds: 10000 # 熔断后休眠时长,默认值5秒 requestVolumeThreshold: 10 # 触发熔断的最小请求次数,默认20 #配置项可以参考 HystrixCommandProperties 类

    • 服务降级
    • 通过HystrixdeCommand的fallback实现服务降级。
    • 服务隔离

    -线程池隔离策略

    – 信号量隔离策略

    Ribbon中使用断路器

  • 在pom.xml中添加依赖
  • org.springframework.cloud spring-cloud-starter-hystrix

  • 在启动类上添加注解开启Hystrix
  • @SpringBootApplication@EnableDiscoveryClient@EnableHystrixpublic class ConsumeServerApplication { public static void main(String[] args) { SpringApplication.run(ConsumeServerApplication.class, args); } @Bean @LoadBalanced public RestTemplate returnBean() { return new RestTemplate(); }}

  • 编写熔断降级逻辑。在方法上加上@HystrixCommand注解,并指定了fallbackMethod熔断方法
  • @ResponseBody@RequestMapping(value = “/info”, method = RequestMethod.GET)@HystrixCommand(fallbackMethod = “backErrorInfo”)public String printInfo() { String url = “http://springbootdemo/backInfo”; return restTemplate.getForObject(url, String.class);}public String backErrorInfo(){ return “sorry,error”;}

  • 测试,如果springbootdemo服务关闭,会发现页面返回了降级处理信息
  • Feign中使用断路器

    SpringCloud Fegin默认已为Feign整合了hystrix

  • 添加配置
  • feign: hystrix: enabled: true # 开启Feign的熔断功能

  • 配置FeignClient接口的实现类,并通过@Component注入到Ioc容器中
  • @Componentpublic class HystrixMethod implements SpringBootFeign { @Override public Map getPerson(int id) { Map map = new HashMap(); map.put(“code”, 500); map.put(“msg”, “sorry,error”); return map; }}

  • 在@FeignClient注解中添加降级方法
  • @FeignClient(name = “springbootdemo”, fallback = HystrixMethod.class)public interface SpringBootFeign { @RequestMapping(value = “/person”, method = RequestMethod.GET) public Map getPerson(@RequestParam(value = “id”) int id);}

  • 关闭 springbootdemo 服务,访问测试
  • Hystrix Dashboard

  • 添加依赖
  • org.springframework.bootspring-boot-starter-actuatororg.springframework.cloudspring-cloud-starter-hystrix-dashboard

  • 在启动类使用@EnableHystrixDashboard注解激活仪表盘
  • @SpringBootApplication@EnableDiscoveryClient@EnableHystrix@EnableHystrixDashboardpublic class ConsumeServerApplication { public static void main(String[] args) { SpringApplication.run(ConsumeServerApplication.class, args); } @Bean @LoadBalanced public RestTemplate returnBean() { return new RestTemplate(); }}

  • 访问页面
  • 遇到问题:https://blog.csdn.net/ghyghost/article/details/108053206

    断路器聚合监控Turbine,Turbine是一个聚合Hystrix 监控数据的工具。

    网关Gateway

    介绍

    Spring Cloud Gateway 是 Spring 官方基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor 等技术开发的网关,旨在为微服务架构提供一种简单而有效的统一的 API 路由管理方式。Spring Cloud Gateway 作为 Spring Cloud 生态系中的网关,目标是替代 Netflflix ZUUL,其不仅提供统一的路由方式,并且基于 Filter 链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。

    快速入门

  • 创建gateway-server模块,引入依赖
  • org.springframework.cloudspring-cloud-starter-gatewayorg.springframework.cloudspring-cloud-starter-netflix-eureka-client

  • 编写启动类
  • @SpringBootApplication@EnableDiscoveryClientpublic class GatewayServerApplication { public static void main(String[] args) { SpringApplication.run(GatewayServerApplication.class, args); }}

  • 编写路由规则
  • server: port: 8765spring: application: # 注册到eureka上的应用名称 name: gateway_server cloud: gateway: #由一个ID、一个目的URL、一组断言工厂、一组Filter组成 routes: # 路由id,可以随意写 – id: consume-server-route # 代理的服务地址 uri: http://127.0.0.1:8081 # 路由断言,可以配置映射路径 predicates: – Path=/person/**eureka: client: # 集群url service-url: defaultZone: http://127.0.0.1:8761/eureka instance: prefer-ip-address: true #使用ip注册 ip-address: 127.0.0.1 instance-id: ${spring.cloud.client.ip-address}:${server.port}

  • 启动测试
  • 路由

  • 添加前缀PrefixPath
  • spring: application: # 注册到eureka上的应用名称 name: gateway_server cloud: gateway: #由一个ID、一个目的URL、一组断言工厂、一组Filter组成 routes: # 路由id,可以随意写 – id: consume-server-route # 代理的服务地址 uri: http://127.0.0.1:8081 # 路由断言,可以配置映射路径 predicates: – Path=/** filters: # 添加请求路径的前缀 – PrefixPath=/person

    相当于PrefixPath=/personhttp://localhost:8765/180868 –》http://localhost:8765/person/180868 –》http://localhost:8081/person/180868

  • 去除前缀StripPrefifix
  • spring: application: # 注册到eureka上的应用名称 name: gateway_server cloud: gateway: #由一个ID、一个目的URL、一组断言工厂、一组Filter组成 routes: # 路由id,可以随意写 – id: consume-server-route # 代理的服务地址 uri: http://127.0.0.1:8081 # 路由断言,可以配置映射路径 predicates: – Path=/api/person/** filters: # 表示过滤1个路径,2表示两个路径,以此类推 – StripPrefix=1

    StripPrefix=1 http://localhost:8765/api/person/180868–》http://localhost:8765/person/180868–》http://localhost:8081/person/180868

  • 动态路由
  • uri以 lb: //开头(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称

    spring: application: # 注册到eureka上的应用名称 name: gateway_server cloud: gateway: routes: # 路由id,可以随意写 – id: consume-server-route # 代理的服务地址 uri: lb://springbootdemo # 路由断言,可以配置映射路径 predicates: – Path=/person/**

  • 重写转发路径
  • 路由转发是直接将匹配的路由path直接拼接到映射路径(URI)之后,那么往往没有那么便利。修改application.yaml

    spring: application: # 注册到eureka上的应用名称 name: gateway_server cloud: gateway: routes: # 路由id,可以随意写 – id: consume-server-route # 代理的服务地址 uri: lb://springbootdemo # 路由断言,可以配置映射路径 predicates: – Path=/springbootdemo/** filters: – RewritePath=/springbootdemo/(?.*), /${segment}

    请求http://localhost:8765/springbootdemo/person/180868 –》http://localhost:8765/person/180868–》http://localhost:8081/person/180868( 值得注意的是在yml文档中 $ 要写成 $ )

  • 基于服务发现的路由规则
  • spring: application: # 注册到eureka上的应用名称 name: gateway_server cloud: gateway: discovery: locator: #设置路由访问方式:http://Gateway_HOST:Gateway_PORT/大写的serviceId/**,其中微服务应用名默认大写访问。 enabled: true # 该设置可以将服务名改成小写(默认为大写) lower-case-service-id: true

    这样,就可以通过http://localhost:8765/springbootdemo/person?id=180868访问

    过滤器

  • 生命周期
    • pre:: 这种过滤器在请求被路由之前调用。
    • post : 这种过滤器在路由到微服务以后执行。
  • 过滤器类型
    • 局部过滤器(GatewayFilter),应用到单个路由或者一个分组的路由上,通过 spring.cloud.gateway.routes.filters 配置在具体路由下,只作用在当前路由上;
    • 全部过滤器(GlobalFilter),应用到所有的路由上,实现 GlobalFilter 接口即可
  • 常见过滤器
  • 过滤器名称

    说明

    AddRequestHeader

    对匹配上的请求加上Header

    AddRequestParameters

    对匹配上的请求路由添加参数

    AddResponseHeader

    对从网关返回的响应添加Header

    StripPrefifix

    对匹配上的请求路径去除前缀

    配置全局默认过滤器

    spring: cloud: gateway: default-filters: – AddResponseHeader=X-Response-Default-MyName, jyd0124

    其他过滤器具体可参考GatewayFilterFactory类

  • 自定义过滤器
  • 需求:模拟一个登录的校验。基本逻辑:如果请求中有token参数,则认为请求有效,放行。
  • @Componentpublic class TokenFilter implements GlobalFilter, Ordered { private final Logger logger = LoggerFactory.getLogger(TokenFilter.class); @Override public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { //request,response都可以通过 ServerWebExchange 获取 String token = exchange.getRequest().getQueryParams().getFirst(“token”); if (StringUtils.isBlank(token)) { logger.info(“token is empty …”); exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); return exchange.getResponse().setComplete(); } //chain.filter 继续向下游执行 return chain.filter(exchange); } @Override public int getOrder() { //过滤器的优先级,返回值越大级别越低 return 0; }}

    跨域问题

    @Configurationpublic class GwCorsFilter { /** * 以下CorsWebFilter跨域处理也可以通过配置文件进行处理 * spring: * cloud: * gateway: * globalcors: * cors-configurations: */ @Bean public CorsWebFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 允许cookies跨域 config.addAllowedOrigin(“*”);// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin config.addAllowedHeader(“*”);// #允许访问的头信息,*表示全部 config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了 config.addAllowedMethod(“OPTIONS”);// 允许提交请求的方法类型,*表示全部允许 config.addAllowedMethod(“HEAD”); config.addAllowedMethod(“GET”); config.addAllowedMethod(“PUT”); config.addAllowedMethod(“POST”); config.addAllowedMethod(“DELETE”); config.addAllowedMethod(“PATCH”); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration(“/**”, config); return new CorsWebFilter(source); } /** * *如果使用了注册中心(如:Eureka),进行控制则需要增加如下配置 */ @Bean public RouteDefinitionLocator discoveryClientRouteDefinitionLocator(DiscoveryClient discoveryClient) { return new DiscoveryClientRouteDefinitionLocator(discoveryClient,new DiscoveryLocatorProperties()); } /** * 以下是springboot2.0.5出现only one connection 的解决办法 * @return */ @Bean public HiddenHttpMethodFilter hiddenHttpMethodFilter() { return new HiddenHttpMethodFilter() { @Override public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { return chain.filter(exchange); } }; }}

    负载均衡和熔断

    Gateway中默认已经集成了Ribbon负载均衡和Hystrix熔断机制。但是所有的策略都是走的默认值,建议根据Ribbon和Hystrix手动进行配置。

    网关限流

    • 计数器限流算法
    • 漏桶算法
    • 令牌桶算法
    • 基于Filter的限流
    • 基于Sentinel的限流

    SpringCloud Config配置中心

    在gitee上创建远程配置文件

    构建config配置中心服务

  • 构建Config-server服务,添加依赖
  • org.springframework.cloudspring-cloud-config-serverorg.springframework.cloudspring-cloud-starter-netflix-eureka-client

  • 在config-server的启动类添加@EnableConfigServer
  • @SpringBootApplication@EnableDiscoveryClient@EnableConfigServerpublic class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); }}

  • 编写config-server配置文件
  • server: port: 8888spring: application: name: config_server cloud: config: server: git: #配置文件所在的git仓库 uri: https://gitee.com/jyd0124/springcloudconfig.git #配置文件分支 default-label: master #配置文件所在根目录 search-paths: config #如果Git仓库为公开仓库,可以不填写用户名和密码,如果是私有仓库需要填写 username: xxx password: xxxeureka: client: service-url: defaultZone: http://127.0.0.1:8761/eureka #服务注册地址

  • 可通过http://localhost:8888/consume-server.yml测试是否成功
  • 获取配置中心配置

  • 改造其他随便一个服务,比如我使用我自己的consume_server,添加依赖
  • org.springframework.cloudspring-cloud-starter-configorg.springframework.cloudspring-cloud-starter-netflix-eureka-client

  • 修改配置
  • 删除consume_server的application.yml 文件(因为该文件从配置中心获取)

    创建consume_server 的bootstrap.yml 配置文件,其内容如下

    spring: cloud: config: name: consume-server # 远程仓库中的版本保持一致 label: master #profile: dev #通过ip直接访问配置中心 #uri: http://localhost:8888/ #通过eurka访问配置中心 discovery: #配置中心服务 service-id: config-server enabled: trueeureka: client: service-url: defaultZone: http://127.0.0.1:8761/eureka #服务注册地址

    3.启动consume_server项目发现获取到配置文件将服务暴露在8081端口,测试接口可成功返回数据

    补充:bootstrap.yml文件也是Spring Boot的默认配置文件,而且其加载的时间相比于application.yml更早。bootstrap.yml文件相当于项目启动时的引导文件,内容相对固定。application.yml文件是微服务的一些常规配置参数,变化比较频繁。

    Spring Cloud Bus服务总线

    问题:

    前面已经完成了将微服务中的配置文件集中存储在远程Git仓库,如果我们更新Git仓库中的配置文件,那用户微服务是否可以及时接收到新的配置信息并更新呢?经过测试,对于Git仓库中配置文件的修改并没有及时更新到用户微服务,只有重启用户微服务才能生效。如果想在不重启微服务的情况下更新配置该如何实现呢? 可以使用Spring Cloud Bus来实现配置的自动更新。

    介绍

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

    具体实现可参考:https://www.fangzhipeng.com/springcloud/2018/08/08/sc-f8-bus.html https://www.cnblogs.com/babycomeon/p/11141160.html

    Spring Cloud体系技术综合应用概览

    来源:https://www.cnblogs.com/jyd0124/p/springcloud.html

    郑重声明:本文内容及图片均整理自互联网,不代表本站立场,版权归原作者所有,如有侵权请联系管理员(admin#wlmqw.com)删除。
    (0)
    用户投稿
    上一篇 2022年6月14日
    下一篇 2022年6月14日

    相关推荐

    • 修完 1300 万行代码,我帮苹果省 2 亿美元,但没拿到承诺的千万股票

      近日,在 Quora(类似知乎)网站上,有 Po 主提出了一个问题:“要使操作系统获得 Unix 认证,需要做些什么?”答主 Terry Lambert 给出了非常精彩的回答,鉴于…

      2022年6月28日
    • 欧阳明高:发展新能源亟须建设储能市场

      中新经纬6月22日电 题:发展新能源亟须建设储能市场 作者 欧阳明高 中国科学院院士、清华大学教授 锂离电子电池的发明使电动汽车发生突飞猛进的变化,带动可再生能源大发展,带来新能源…

      2022年6月24日
    • Python和Java二选一该学啥?

      Python和Java二选一该学啥? 有网友说Python和Java之间选择一门进行学习,现在很纠结该选哪个。不知道这两种语言都有什么前景? 选java,选java,选java!!…

      2022年6月27日
    • 果然好用的粉底液都是我平常用的,小众国货粉底也纷纷上榜

      粉底液对于我来说一直就很重要 毕竟它是会影响我的整个妆面 一旦选不对就会出现卡粉脱妆等一系列的问题 所以一定要好好选 大家根据自己的肤质去选择 测试下来果然不氧化就是我平常用的最多…

      2022年7月1日
    • 300211亿通科技

      #我在头条搞创作# 股权转让关联理由121年1月,安徽顺源成为公司的控股股东,黄汪成为实际控制人 广电关联理由 广播电视设备制造商;有线电视网络光传输设备、同轴电缆传输设备以及数据…

      2022年6月13日
    • Git从入门到精通,Git命令大全

      原文:Git从入门到精通,Git命令大全-友人a的笔记丶 Git入门 资料来源:https://www.runoob.com/git/git-tutorial.html、http:…

      2022年7月11日
    • 庄周梦蝶终非蝶,冷静看待“谷歌AI形成人格”事件

      事件背景:6月13日,《华盛顿邮报》消息称,41岁谷歌软件工程师Blake Lemoine以内部邮件的形式声称谷歌于2021年I/O大会上推出的对话AI系统LaMDA已经具有人格,…

      2022年6月16日
    • 一招教你如何让正在玩耍的孩子乖乖回家

      大家最近带娃出门有没有看到一种现象,家长在前面气冲冲的埋头走,小朋友在后面哭着追? 处于暑假期间,我最近带娃出门比较多,也接触到很多家长和小朋友。我发现有些家长跟小朋友的交流方式存…

      2022年8月19日
    • 拉黑再删除永久加不上(微信该用户不存在是拉黑了吗)

      很多用户明明获得了对方的微信号,但通过微信添加功能搜索时,却显示“用户不存在”,本期文章结合微信的机制,说说是什么原因导致的这种情况,以及该如何解决。 一、输入错误 正常情况下,搜…

      2022年11月5日
    • 从计算机焦虑到计算焦虑:超算云服务正应时

      来源:【科学网】 浙江大学研究员王海鸥长期从事湍流燃烧的基础和应用研究,这项研究需要借助超级计算机,揭示工业燃烧装置中湍流燃烧的复杂规律。 尽管如此,王海鸥并不必泡在实验室,也能随…

      2022年7月1日

    联系我们

    联系邮箱:admin#wlmqw.com
    工作时间:周一至周五,10:30-18:30,节假日休息