SpringCloud的五大神兽的详细配置

RestTemplate

  • pom文件
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • 配置类
@Configuration
public class CustomConfiguration {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
  • 调用服务【Controller类中提供】
@RestController
public class DeptController {
    private static String prefix_url = "http://localhost:8001";
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/consumer/query/{id}", method = RequestMethod.GET)
    public Dept query(@PathVariable("id") Long id) {
        System.out.println(prefix_url + "/query/" + id);
        Dept dept = restTemplate.getForObject(prefix_url + "/query/" + id, Dept.class);
        return dept;
    }
    @RequestMapping("/consumer/save")
    public void save(Dept dept) {
        System.out.println(dept);
        restTemplate.postForObject(prefix_url + "/save", dept, String.class);
    }
}
注意:Eureka服务端及其客户端、Ribbon和Feign、Hystrix、Zuul的依赖都是spring-cloud-starter-xxx形式
	 分布式配置中心的服务端、客户端的依赖是spring-cloud-config-xxx形式,其中分布式配置中心客户端有两种      依赖,其中也是spring-cloud-starter-xxx形式,建议写前一种,方便与服务端对应
切记:Eureka服务端的依赖是spring-cloud-starter-netflix-eureka-server,如果写成了spring-cloud-netflix-eureka-server,那么服务无法注册到注册中心----已经犯过错了
Eureka Server
  • pom文件
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
  • 配置文件application.yml
server:
  port: 7001
eureka:
  instance:
    hostname: server01 #注册中心的名称
  client:
    fetch-registry: false  #不获取服务
    register-with-eureka: false #不向注册中心注册服务,自己就是注册中心
    service-url:
      defaultZone: http://localhost:7002/eureka/  #集群配置配置其他注册中心的地址
      # defaultZone: http://localhost:7002/eureka/ #单机则配置自己的地址
  • 入口启动类加注解:@EnableEurekaServer
@SpringBootApplication
@EnableEurekaServer
public class EurekaserverApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaserverApplication.class, args);
    }
}
Eureka Client
  1. 服务提供方-----切记:服务提供方集群的时候,服务名称必须一致,否则就不是集群了,负载均衡也不起作用
  • pom文件
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • 配置文件application.yml
server:
  port: 8001
#给指定包配置别名【springboot不支持通配符,在另外配置java代码才能支持】
mybatis:
  type-aliases-package: top.onething.common.domain
#不配置此属性时,默认在classpath下与mapper接口的层级结构相同的目录下,一般在resouces下建目录结构
  mapper-locations: classpath:mapper/*Mapper.xml
  #当需要xml中配置mybatis时,才需要配置mybtis配置文件的位置
  #config-location: classpath:mybaits-config.xml
  configuration:
    #mybatis日志,在控制台看sql语句
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#分页插件配置
pagehelper:
  reasonable: true
#连接池的配置
spring:
  datasource:
    url: jdbc:mysql:///department?useUnicode=true&characterEncoding=utf-8&useSSL=false
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
  application:
    name: provider01
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka,http://localhost:7002/eureka #告知服务提供者注册中心的地址
  instance:
    prefer-ip-address: true  #设置后,鼠标在instance_id上,浏览器左下角显示ip地址
info:  #配置info信息,鼠标点击instance_id后显示的信息,一般配置应用的相关介绍,方便用户查看
  msg: 欢迎光临!

  • 入口启动类
@SpringBootApplication
@EnableEurekaClient
@MapperScan(basePackages = "top.onething.provider.mapper")
public class ProverApplication8001 {
    public static void main(String[] args) {
        SpringApplication.run(ProverApplication8001.class, args);
    }
}

2.服务消费方

  • Pom文件
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

  • 配置yaml文件
server:
  port: 9002
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/

  • 入口启动类
@SpringBootApplication
@EnableEurekaClient
public class Consumer2Application {
    public static void main(String[] args) {
        SpringApplication.run(Consumer2Application.class, args);
    }
}

  • 远程调用对象RestTemplate
@Configuration
public class CustomConfiguration {
    @Bean
    @LoadBalanced//Ribbon是客户端的负载均衡器
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

  • 实现服务调用
@RestController
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    private static String URL_PREFIX = "http://SERVICE-PROVIDER";

    @RequestMapping("/user/{id}")
    public User getRestTemplate(@PathVariable("id") Long id) {
        String url = URL_PREFIX + "/user/" + id;
        return restTemplate.getForObject(url, User.class);
    }
}

Eureka和Zookepeer的区别:

  • 分布式系统存在多台服务器,网络故障必定存在,必须遵守P原则,因此只能选择AP、CP
  • Eureka遵守AP原则,Zookepeer遵守CP原则
  • RDBMS遵守CA原则,MongoDB、HBase、Redis遵守CP原则

集群时,各服务器的同一功能的服务需配置同一个服务名

负载均衡
Ribbon
  • 负载均衡的作用:
  1. 转发:在用户请求时,转发请求的功能
  2. 故障移除:如果这一台机器挂了,负载均衡服务器不会再把请求转发到这台服务器
  3. 恢复添加:如果这一台机器恢复正常了,负载均衡服务器会把它重新添加回来

Ribbon是客户端负载均衡器,提供客户端的负载均衡算法,Ribbon默认使用轮询策略

负载均衡Load Balance,简写LB,将用户的请求平摊到多个服务上,使系统达到高可用。

常见的负载均衡策略:轮询策略、随机轮询、根据响应时间的加权轮询、Retry轮询【正常情况下轮询,某个服务器宕机了则在指定时间内重试【注意:重试访问不行直接返回错误】,仍然不行就不在重试,不再调用访问该服务器】

常见负载均衡软件:Nginx

常见负载均衡硬件:F5

  • 消费方pom文件中引入依赖:spring-cloud-starter-netflix-ribbon
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

  • 配置类进行配置------消费方配置
  1. 如果采用Ribbon默认的轮询策略,则配置类中,获取用RestTemplate对象的方法上加注解@LoadBalanced,然后直接使用RestTemplate对象进行服务的远程调用即可
@Configuration
public class CustomConfiguration {
    @Bean
    @LoadBalanced//Ribbon是客户端的负载均衡器
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

  1. 如果要选用其他的负载均衡策略
@Configuration
public class CustomConfiguration {
    @Bean
    @LoadBalanced//Ribbon是客户端的负载均衡器
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    //配置获取策略对象的方法
    @Bean
    public IRule rule(){
        return new RandomRule();
    }
}

Feign

Feign是一个声明式的web服务【webservice】客户端,只需创建一个接口,然后在接口和接口内的方法上加注解,将指定的服务与接口进行绑定

(1)Ribbon是负载均衡器,Feign是Http客户端
(2)spring cloud两种负载均衡的实现方式:ribbon和feign
(3)Feign的spring-cloud-starter-openfeign依赖集成了Ribbon和Hystrix,实际feign负载均衡底层是使用Ribbon实现的
(4)Feign按如下方式配置好后,就已经实现了负载均衡功能,默认Feign的负载均衡策略是:轮询策略
(5)如果需要使用自定义策略或内置策略,更换方式与Ribbon相同,需要自定义配置类进行修改

  • 消费方pom文件引入依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 注意:spring-cloud-starter-openfeign的版本号与spring-cloud的版本号不一致-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.1.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

  • yaml文件配置
server:
  port: 9003
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/

  • 创建调用服务的接口,将接口和指定的服务名进行绑定
@FeignClient(value = "PROVIDER")//将接口与指定的服务名进行绑定
public interface IDeptService {
    
    //接口中方法的映射路径应该与服务提供方提供服务的映射路径保持一致
    @RequestMapping(value = "/query/{id}")
    public Dept query(@PathVariable("id") Long id);

    @RequestMapping(value = "/del/{id}")
    public void delete(@PathVariable("id") Long id);
}

  • Controller层调用服务
@RestController
public class DeptController {

    @Autowired
    private IDeptService deptService;//注入动态代理生成接口的实现类实例

    @RequestMapping(value = "/query/{id}",method = RequestMethod.GET)
    public Dept query(@PathVariable("id") Long id){
        Dept dept = deptService.query(id);
        System.out.println("======查询==========");
        return dept;
    }

    @RequestMapping(value = "/del/{id}",method = RequestMethod.GET)
    public void delete(@PathVariable("id") Long id) {
        deptService.delete(id);
        System.out.println("=====删除==========");
    }
}

  • 入口类打注解@
//因为feign在消费方,消费方是客户端
//开启feign,spring才会扫描入口类所在包的当前包及其子子孙孙包中的服务接口,接口上必须有注解@EnableFeignClients,动态代理生成接口的实现类实例
//当服务接口不在入口类所在包的当前包及其子子孙孙包中时,需要指定扫描的包:@EnableFeignClients(basePackages ="包名")-----但建议都指定要扫描的包

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages={"top.onething.consumer3.service"})
public class Consumer3Application {
    public static void main(String[] args) {
        SpringApplication.run(Consumer3Application.class, args);
    }
}

Hystrix断路器

Hystrix是一款容错框架,有效的解决了雪崩效应

  • 雪崩效应:某个微服务故障,而该微服的瞬时访问量大或被大量被其他服务调用时,就会大量消耗系统的线程、IO等资源,导致系统崩溃。

Hystrix断路器:当某个微服务故障,通过断路器的故障监控,向调用方返回一个符合预期的、可处理的备选响应(FallBack),而不是长时间等待或抛出调用方无法处理的异常,从而避免雪崩效应。

Hystix断路器的四种机制:隔离、熔断、降级(FallBack)、缓存

  • 隔离:为不同的服务分配一定的资源,当自己的资源用完,直接降级处理而不是占用别人的资源。

    ​ Hystrix隔离模式分为两种:线程池隔离和信号量隔离

    ​ hystrix默认采用线程池隔离

  • 熔断:当某个服务微持续调用失败,达到一定阈值(默认5s内调用失败20次),Hystrix断路器进入熔断状态,一段时间内对该微服务的调用都会被拒绝,进行降级处理,返回备选响应。一段时间后Hystrix熔断器会进入半熔断状态,允许少量请求尝试调用该微服务,调用失败则回到熔断状态,调用成功则恢复正常

  • 降级:调用服务异常或服务异常时,向调用方返回一个符合预期的、可处理的备选响应,而不是长时间等待或抛出调用方无法处理的异常

  • 缓存:hystrix支持将一个请求结果缓存起来,下一个具有相同key的请求将直接从缓存中取出结果

非feign客户端配置Hystrix断路器
  1. 服务提供方的pom文件引入断路器Hystrix的依赖包:spring-cloud-starter-netflix-hystrix
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

  1. yaml配置文件可以不对Hystrix进行配置
  2. 在服务提供方需要配置断路器的方法上,添加【@HystrixCommand(fallbackMethod = “降级处理时调用方法的名称”)】,并编写降级处理时调用方法【该方法的返回类型、参数类型必须与配置断路器的方法相同】
    • 降级:调用某个方法一旦失败,向调用方返回一个符合预期、可处理的备选响应。
    • 熔断:调用某个方法持续出错,达到阀值,熔断器进入熔断状态,一段时间内调用该方法的所有请求都会被拒绝,一定时间后熔断器自动进入半熔断状态,允许少量请求尝试调用,调用失败则回到熔断状态,调用成功,恢复正常
@RestController
public class ProviderController {
    @RequestMapping(value = "/query/{id}")
    @HystrixCommand(fallbackMethod = "failQuery")
    public Dept query(@PathVariable("id") Long id) {
        if (id == 2000) {
            throw new RuntimeException("该用户不存在");
        }
        Dept dept = iDeptService.selectByPrimaryKey(id);
        System.out.println("我是3号服务提供者");
        return dept;
    }

    public Dept failQuery(Long id) {
        Dept dept = new Dept();
        dept.setId(id);
        dept.setName("用户不存在");
        dept.setSource("未知");
        return dept;
    }
}

  1. 入口类加注解@EnableHystrix
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
@MapperScan(basePackages = "top.onething.provider.mapper")
public class ProverApplication8003 {
    public static void main(String[] args) {
        SpringApplication.run(ProverApplication8003.class, args);
    }
}

feign客户端配置Hystrix断路器
  1. 服务消费方pom文件引入依赖 【注意:Feign的依赖中已经集成了Hystrix的依赖和Ribbon的依赖】
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 注意:spring-cloud-starter-openfeign的版本号与spring-cloud的版本号不一致-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.1.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

  1. yaml配置文件中feign.hystrix.enabled=true必须配置,各种超时相关的配置可以视情况可配可不配
server:
  port: 9004
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/
feign:
  hystrix:
    enabled: true #开启hystrix断路器功能
  client:
    config:
      remote-service:   #服务名,default为所有服务
        connectTimeout: 3000 #配置feign的连接超时  客户端与服务端建立连接的时间
        readTimeout: 3000 #配置feign的读取超时 客户端读取到服务端可用资源的时间
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000 #设置hystrix的超时时间

  1. 配置服务接口,通过注解@FeignClient(value=“微服务名”,fallbackFactory=“降级处理的类.class”),绑定微服务名,指定降级处理的类
    • 降级处理的类必须打注解@Component,以便spring创建对象
    • 降级处理的类必须实现接口:FallbackFactory<需要降级处理的接口类型>,并指定泛型为需要降级处理的接口类型
//降级处理时调用的类
@Component
public class DeptServiceFallbackFactory implements FallbackFactory<IDeptService> {
    @Override
    public IDeptService create(Throwable throwable) {
        return new IDeptService() {
            @Override
            public Dept query(Long id) {
                System.out.println("=========查询异常==========");
                Dept dept = new Dept();
                dept.setId(id);
                dept.setName("return");
                dept.setName("数据源未知");
                return dept;
            }

            @Override
            public String delete(Long id) {
                System.out.println("===删除服务处于熔断状态===");
                return "删除异常"}
        };
    }
}

//服务接口
@FeignClient(value = "PROVIDER", fallbackFactory = DeptServiceFallbackFactory.class)
public interface IDeptService {
    //接口中方法的映射路径应该与服务提供方提供服务的映射路径保持一致
    @RequestMapping(value = "/query/{id}")
    public Dept query(@PathVariable("id") Long id);

    @RequestMapping(value = "/del/{id}")
    public void delete(@PathVariable("id") Long id);
}

  1. 入口类配置【注意入口类不需要配置@EnableHystrix】
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages={"top.onething.consumer4.service"})
public class Consumer4Application {
    public static void main(String[] args) {
        SpringApplication.run(Consumer4Application.class, args);
    }
}

Hystrix除了容错以外,还提供了近乎实时的服务调用监控,持续记录用户请求的执行信息。

Hystrix Dashboard服务监控是一个独立的微服务,通过调用该微服可以监控其他微服务。

Zuul

Zuul 网关主要有两个功能:路由请求、过滤请求

  • 路由请求:对外提供了统一入口,屏蔽了内部细节
  • 过滤功能:对请求的处理过程进行干预,实现请求校验、服务聚合等功能

Zuul将自身注册到Eureka注册中心,同时从注册中心获取其他微服务的信息,访问微服务都需要通过Zuul跳转

  1. 路由的基本配置
  • pom文件引入zuul的相关依赖

Feign和Zuul的依赖spring-cloud-starter-netflix-zuul集成了Ribbon和Hystix,负载均衡策略均使用轮询策略。

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

  • yaml配置文件
server:
  port: 9527
spring:
  application:
    name: zuul-gateway
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/, http://localhost:7002/eureka/
  instance:
    prefer-ip-address: true
zuul:
  ignored-services: "*"   #"*":忽略所有微服务,也可以配置单个微服名
  prefix: /test  #外部访问时添加统一的前缀,http://localhost:8888/a/1在配置后http://localhost:8888/test/a/1
  routes:
    #微服务名称:映射路径
    provider: /deptservice/**
    #忽略的微服名,不能通过【通过http://IP地址:端口号/微服务名/提供微服务的服务器内部URI】进行访问

  • 入口类配置@EnableZuulProxy注解,开启zuul的配置
@SpringBootApplication
@EnableZuulProxy//开启Zuul相关的配置
public class ZuuApplication9527 {
    public static void main(String[] args) {
        SpringApplication.run(ZuuApplication9527.class, args);
    }
}

  • 配置好以后,通过http://IP地址:端口号/微服务名/提供微服务的服务器内部URI

举例:http://localhost:9527/provider/query/2222

  1. 映射规则的配置
zuul:
  ignored-services: "*"   #"*":忽略所有微服务,也可以配置单个微服名,配置以后外部就无法通过服务名进行访问
  prefix: /test  #外部访问时添加统一的前缀,http://localhost:8888/a/1在配置后http://localhost:8888/test/a/1
  routes:
    #微服务名称:映射路径
    provider: /deptservice/**
    #忽略的微服名,不能通过【通过http://IP地址:端口号/微服务名/提供微服务的服务器内部URI】进行访问

Config Server

单点配置中心的执行流程:分布式配置中心的客户端请求分布式配置中心,分布式配置中心从github上面获取指定的配置文件

注意:配置中心需要集群时,配置中心的客户端实际是从Eureka中心获取的配置中心提供的服务,详解配置中心的高可用。


github保存的配置文件内容必须是UTF-8格式

分布式配置中心分为两部分:服务端和客户端

服务端集中管理github上的配置文件

  • github上创建仓库后,克隆github上的仓库到本地磁盘,将需要管理的配置文件上传github
  • pom文件
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>
</dependencies>

  • YAML配置文件
spring:
  application:
    name: configserver
  cloud:
    config:
      server:
        git:
          #如果URI配置的ssh地址,则不需要配置用户名和密码
          uri: https://github.com/sky2sea2020/eshop-config.git
          #如果Git仓库为公开仓库,可以不填写用户名和密码,如果是私有仓库需要填写
          #username: sky2sea
          #password: 123456

假如需要设置分布式配置中心从本地配置文件获取配置信息,而不是从git,则详见下面配置:

(1)设置启动方式
设置从本地获取配置文件,而不是从git:
spring.profiles.active=native
(2)设置获取的本地配置文件位置
如果分布式配置中心不从github上获取配置文件,而直接从本地磁盘获取,则配置如下:
spring.cloud.config.server.native.search-locations=磁盘文件的绝对地址 或者 calasspath:文件路径【放在zuul微服务的resources目录中】

spring:
  profiles:
    active: native
  application:
    name: config-server
  cloud:
    config:
      server:
        native:
          search-locations: classpath:/

  • 入口类加注解@EnableConfigServer
@EnableConfigServer
@SpringBootApplication
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

  • 通过http://配置中心IP地址:端口号/配置文件名-配置文件中的环境名.yml访问,如果能看到对应环境下的配置信息,则分布式配置中心与github通信正常。
Config Client

分布式配置中心的客户端有可能是Eureka注册中心、服务消费者、服务提供者、Zuul等

  • pom文件:分布式配置中心的客户端必须引入的两个依赖:spring-boot-starter-web【此模块必须有,佛祖保存】、spring-cloud-starter-config(或spring-cloud-config-client)【前者包含了后者,二选一】

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    
  • yaml配置文件

#bootstrap.yml配置文件的配置如下:【下面的配置必须有】
spring:
  cloud:
    config:
      name: configclient #对应github上存放的配置文件名称
      profile: prod #对应github上配置文件中的profile属性
      label: master #对应github上仓库的分支名
      uri: http://127.0.0.1:3344 #配置服务器
#application.yml配置文件的配置如下:【下面的配置只是举例】
spring:
  application:
    name: hello
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka,http://localhost:7002/eureka
  instance:
    prefer-ip-address: true

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

  • github仓库中存放的配置文件,下面的bootstrap.yml配置文件只是举例而已:
spring:
  profiles:
    active: test
---
server:
  port: 6001
spring:
  profiles: dev
  application:
    name: dev
---
spring:
  profiles: test
  application:
    name: test
server:
  port: 6002
---
spring:
  profiles: prod
  application:
    name: prod
server:
  port: 6003

注意:配置中心的客户端的依赖必须有如上配置,但配置中心客户端一般是注册中心、服务提供者、服务消费者、Zuul,因此还需要在此基础上添加它们的依赖和配置

通过注解@Value可以从配置文件中获取配置属性值
@RestController
public class DemoController {
    @Value("${server.port}")
    private String port;
    @Value("${spring.application.name}")
    private String name;

    @RequestMapping("/test")
    public String test() {
        return port + ":" + name;
    }
}

Yaml配置文件详解

Springboot有两种类型的配置文件:bootstrap.yml、application.yml,都默认在classpath路径下进行加载

  • bootstrap.yml和application.yml的区别:
  1. application.yml配置文件是当前应用级别的配置文件,bootstrap.yml配置文件是系统级别的配置
  2. bootstrap.yml优先级高于application.yml,application.yml的配置不能覆盖bootstrap.yml的配置,优先使用bootStrap.yml的配置
  3. bootstrap.yml配置文件用于分布式配置中心获取github上指定仓库、指定分支、指定文件、指定环境的配置信息
  • YAML配置文件格式:UTF-8

配置文件格式必须为utf-8,否则无法正常读取配置文件内容而报错:java.nio.charset.MalformedInputException


#bootstrap.yml中关于分布式配置中心客户端的配置信息
spring:
  profiles:
    active: test  #设置默认激活的环境
  cloud:
    config:
      name: plat-service
      profile: ${spring.profiles.active} #通过表达式方便指定激活的环境
      label: master #对应github上仓库的分支名
      # uri: http://localhost:3344 #配置中心直接通过配置中心获取配置信息时,才这么配置
      discovery:
        enabled: true #设置为true时,开启通过注册中心获取服务名,来访问Config Server的功能
        service-id: CONFIGSERVER #指定Config Server注册的服务名【集群时各服务器的服务名统一设置为一个】

  • Spring Cloud会将配置映射为URI:/{application}/{profile}

  • 浏览器通过配置中心访问仓库中配置文件的URI,共用三种访问形式:

    /{application}/{profile}[/{label}]-------分支名{lable}是可以省略的,默认是master分支

    /{application}-{profile}.yml/{application}-{profile}.properties

    /{label}/{application}-{profile}.yml或/{label}/{application}-{profile}.properties

  • github仓库中配置文件名的形式一般为:{application}-{profile}.yml,访问建议使用:/{application}/{profile}

    如果配置文件名为:{application}.yml,访问建议使用:/{application}/任意字符串

  • bootstrap.yml的配置信息与仓库中配置文件的映射关系:

    • spring.cloud.config.name对应:配置文件名称的{application}部分

      不配置时,默认为配置文件中spring.application.name的属性值

    • spring.cloud.config.profile对应:配置文件名称的{profile}部分

      不配置时,profile默认为default

    • spring.cloud.config.label对应:github仓库分支命的名称

      不配置时,默认为null,但访问仓库时默认访问master分支

  • 假设只配置了spring.cloud.config.name=hi,没有配置spring.cloud.config.profile、spring.cloud.config.label,则默认profile为default,默认lable为master,映射的URL为:

    http:IP地址:端口号/hi/任意字符串

    http:IP地址:端口号/hi-任意字符串.yml

    http:IP地址:端口号/master/hi-任意字符串.yml

  • 假设配置spring.cloud.config.name=hi,spring.cloud.config.profile=dev,spring.cloud.config.lable=test,则映射的URL为:

    http:IP地址:端口号/hi/dev

    http:IP地址:端口号/hi-dev.yml

    http:IP地址:端口号/test/hi-dev.yml

配置中心高可用

当需要通过集群来实现配置中心的高可用时,上面的配置就存在问题。

  1. 配置中心:需要注册服务到服务注册中心
  • Pom文件
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

  • yaml配置文件
spring:
  application:
    name: configserver
  cloud:
    config:
      server:
        git:
          #如果URI配置的ssh地址,则不需要配置用户名和密码
          uri: https://github.com/sky2sea2020/eshop-config.git
          #如果Git仓库为公开仓库,可以不填写用户名和密码,如果是私有仓库需要填写
          #username: sky2sea
          #password: 123456
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka #告知服务提供者注册中心的地址
  instance:
    prefer-ip-address: true  #设置后,鼠标在instance_id上,浏览器左下角显示ip地址

  • 入口类
@EnableConfigServer
@EnableEurekaClient
@SpringBootApplication
public class ConfigServerApp {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApp.class, args);
    }
}

  • Eureka注册中心发现配置中心提供的服务
  1. 配置中心的客户端:从服务中心发现配置中心提供的服务,并通过服务名调用配置中心提供的服务
  • pom文件
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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-client</artifactId>
</dependency>

  • application.yml的配置
server:
  port: 8001
spring:
  application:
    name: eshop-plat

  • bootstrap.yml的配置
spring:
  profiles:
    active: test  #设置默认激活的环境
  cloud:
    config:
      #github仓库中配置文件名的形式一般为:{application}-{profile}.yml
      name: plat-service #对应github上配置文件名称的{application}部分
      profile: ${spring.profiles.active} #对应github上配置文件名称的{profile},注意区分多文档块形式的配置文件
      label: master #对应github上仓库的分支名
      # uri: http://localhost:3344 #配置中心直接通过配置中心获取配置信息时,才这么配置
      discovery:
        enabled: true #设置为true时,开启通过注册中心获取服务名,来访问Config Server的功能
        service-id: CONFIGSERVER #指定Config Server注册的服务名【集群时各服务器的服务名统一设置为一个】
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/
  instance:
    prefer-ip-address: true

  • 入口类
@SpringBootApplication
@EnableEurekaClient
public class PlatApp {
    public static void main(String[] args) {
        SpringApplication.run(PlatApp.class, args);
    }
}

注意:Eureka注册中心、分布式配置中心的配置文件不能放在github上面

  • 因为配置中心高可用的配置中,是通过注册中心获取分布式配置中心提供的服务,如果注册中心都未运行,则无法获取配置中心的 配置文件。
各微服务的打包发布
  • Pom文件引入springboot项目maven打包的插件
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>2.1.1.RELEASE</version>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>

  • 在项目的最外层父项目运行maven install命令【IDEA界面右侧的maven生命周期的install插件】,将各模块生成的依赖包安装到本地maven仓库,运行IDEA界面右侧的maven生命周期的package插件
    • maven install实际上就是将测试、编译、打包好的包安装到本地仓库,当其他项目依赖这些包时,打包的时候就可以直接引入。
  • 在jar包所在目录运行dos命令:java -jar -Dspring.profiles.active=dev jar包或war包名,发布项目
    • 命令中的-Dspring.profiles.active=dev:环境切换
微服务各模块启动顺序

微服务注册中心

分布式配置中心

Zuul网关

各微服务

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是一些常见的神兽的 ASCII 艺术: 1. 麒麟 ``` ,#####, #_ _# |a` `a| | u | \ = / |\___/| ___/\_`.___.'_/\___ /.---.\|` `||/.---.\ ' `--. `\\ //` .--` ` `\\ \\ // //` `\\//\\//` `\/\//\/` `"`"`` ``` 你可以将上面的 ASCII 艺术复制到代码中,使用 printf 函数打印出来。 例如: ``` #include <stdio.h> int main() { printf(" ,#####,\n"); printf(" #_ _#\n"); printf(" |a` `a|\n"); printf(" | u |\n"); printf(" \\ = /\n"); printf(" |\\___/|\n"); printf(" ___/\\_`.___.'_/\\___\n"); printf(" /.---.\\|` `||/.---.\\\n"); printf("' `--. `\\\\ //` .--` `\n"); printf(" `\\\\ \\\\ // //`\n"); printf(" `\\\\//\\\\//`\n"); printf(" `\\/\\//\\/`\n"); printf(" `\"`\"`\"\n"); return 0; } ``` 2. 凤凰 ``` ____......----""""----......____ ."" . . "". .'' ...'''''''--... ``. .' ..'._._._._._._._.''. `. .' .'.' `.`. `. . .'.' `. . . .' `. . . .' `. . . .' `. . . .' `. . . .' `. . . .' `. . . . . . . . . . . . . . . . . `. . . `. . . `. . . `.`. . . `.`. . `. `.`. . `. `.`. . `. `.`. . `. `.`. . `. """"----....____,..::''''' | __ ,' / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | / | /_______________________________________________| ``` 同样,你可以将上面的 ASCII 艺术复制到代码中,使用 printf 函数打印出来。 ### 回答2: 使用printf函数可以打印出一个神兽的图案。首先,我们需要使用转义字符和特定的符号来组成图案。例如,可以使用星号(*)来表示神兽的眼睛和鼻子,用斜杠(/)和竖线(|)来表示神兽的身体和四肢。下面是一个示例: ``` #include <stdio.h> int main() { printf(" /\\_/\\\n"); printf(" ( o.o )\n"); printf(" (> <)\n"); printf(" -~~-"); return 0; } ``` 上面的代码会打印出一个小猫的图案,这可以被视为一种神兽的形象。其中,第一行和最后一行使用了斜杠(/)表示神兽的额头和下巴,而第二行和第三行使用了星号(*)表示神兽的眼睛和鼻子,最后一行使用了连字符(-)和波浪线(~)表示神兽的身体。 希望以上的回答能帮到您! ### 回答3: 在使用printf打印神兽时,我们需要事先准备好神兽的图案。通常,我们可以使用ASCII字符来组成神兽的形状。以下是一个示例的代码段: ```c #include <stdio.h> int main() { printf(" />  フ\n"); printf("      |  _  _| \n"); printf("  /`ミ_xノ |\n"); printf("  /      |\n"); printf(" │  >  ≫|\n"); printf(" /    /   |\n"); printf(" | ト   |  |\n"); printf(" ┴─┴   ヽ  \n"); printf(" ノ |     \n"); printf(" |  _     |\n"); printf(" │  U   \n"); printf(" \     \n"); return 0; } ``` 在上述代码中,我们使用ASCII字符来呈现了一只神兽的形象。我们使用printf函数逐行打印出神兽的图案,从而实现了打印神兽的效果。运行该程序,即可在终端或控制台上看到如上图案的神兽。 当然,如果你有其他神兽的图案,也可以根据相应的ASCII字符来打印。需要注意的是,每个字符之间需要使用`\n`进行换行,以保证打印结果的准确性。 总而言之,使用printf函数打印神兽,只需准备好相应的ASCII字符,并使用printf函数逐行打印它们,即可在终端或控制台上看到神兽的形象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值