SpringClould

一、架构简介

单一应用架构 :主要解决ORM 数据库访问层。
垂直应用架构 : 解决分层问题,实现应用的分层开发,提升开发效率。
分布式应用架构:解决系统间调用问题,引发了SOA(面向服务开发)架构新潮。
SOA治理(Macro Service治理):对面向服务开发和治理同时提出新的挑战,要求应用能够做到容易部署、智能路由、服务负载均衡、熔断等要求,能够做到对服务的可视化治理等。
在这里插入图片描述

  • 随着互联网的发展,人们对这种微服务的开发的呼声越来越大,在互联网的萌芽了两款重量级的SOA治理框架阿里巴巴Dubbo和SpringFrameWork提供的SpringCloud由于Spring的广大使用群体也间接的使的Spring Cloud的市场占用率一路飙升。阿里巴巴的Dubbo也开始发力,由于阿里巴巴的优秀的技术团队和国内较高的知名度,也对Dubbo框架的发展起到一定的推广的作用,但是相比较于SpringCloud而言,dubbo由于易用性上和对程序员的要求都比Spring Cloud要高一些,因此目前很多互联网公司在做微服务组件开发的时候一般还是使用SpringCloud居多。

二、注册中心 Eureka 的部署

2.1 pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

2.2 启动配置类

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

2.3 properties配置

  • application-eureka-1.properties
server.port=1111

# 指定当前注册中心的服务名称
spring.application.name=eurekaregistry

## 启用注册中心主动失效,并且每次主动失效检测间隔为5s 默认值60s
eureka.server.eviction-interval-timer-in-ms= 5000
## 设置eureka注册中心的响应更新时间
eureka.server.responseCacheUpdateIntervalMs=3000
eureka.server.responseCacheAutoExpirationInSeconds=60

## 配置注册中心的主机名
eureka.instance.instance-id = eureka-1
eureka.instance.hostname = CentOSA
## 服务刷新时间配置,每隔这个时间会主动心跳一次
eureka.instance.lease-renewal-interval-in-seconds= 5
## 服务提供者被认定为丢失心跳超时,失效多久后被删除
eureka.instance.lease-expiration-duration-in-seconds=15

## 配置定时获取|抓取注册中心的数据时间
eureka.client.registry-fetch-interval-seconds= 5
eureka.client.instance-info-replication-interval-seconds= 5
## 配置集群中其他eureka实例,用于本eureka实例的注册方。
eureka.client.region=beijing
eureka.client.availability-zones.beijing=zone-2,zone-3
eureka.client.service-url.zone-2=http://CentOSB:1111/eureka/
eureka.client.service-url.zone-3=http://CentOSC:1111/eureka/
  • application-eureka-2.properties
server.port=1111

# 指定当前注册中心的服务名称
spring.application.name=eurekaregistry

## 启用注册中心主动失效,并且每次主动失效检测间隔为5s 默认值60s
eureka.server.eviction-interval-timer-in-ms= 5000
## 设置eureka注册中心的响应更新时间
eureka.server.responseCacheUpdateIntervalMs=3000
eureka.server.responseCacheAutoExpirationInSeconds=60

## 配置注册中心的主机名
eureka.instance.instance-id = eureka-2
eureka.instance.hostname = CentOSB
## 服务刷新时间配置,每隔这个时间会主动心跳一次
eureka.instance.lease-renewal-interval-in-seconds= 5
## 服务提供者被认定为丢失心跳超时,失效多久后被删除
eureka.instance.lease-expiration-duration-in-seconds=15

## 配置定时获取|抓取注册中心的数据时间
eureka.client.registry-fetch-interval-seconds= 5
eureka.client.instance-info-replication-interval-seconds= 5
## 配置集群中其他eureka实例,用于本eureka实例的注册方。
eureka.client.region=beijing
eureka.client.availability-zones.beijing=zone-1,zone-3
eureka.client.service-url.zone-1=http://CentOSA:1111/eureka/
eureka.client.service-url.zone-3=http://CentOSC:1111/eureka/
  • application-eureka-3.properties
server.port=1111

# 指定当前注册中心的服务名称
spring.application.name=eurekaregistry

## 启用注册中心主动失效,并且每次主动失效检测间隔为5s 默认值60s
eureka.server.eviction-interval-timer-in-ms= 5000
## 设置eureka注册中心的响应更新时间
eureka.server.responseCacheUpdateIntervalMs=3000
eureka.server.responseCacheAutoExpirationInSeconds=60

## 配置注册中心的主机名
eureka.instance.instance-id = eureka-3
eureka.instance.hostname = CentOSC
## 服务刷新时间配置,每隔这个时间会主动心跳一次
eureka.instance.lease-renewal-interval-in-seconds= 5
## 服务提供者被认定为丢失心跳超时,失效多久后被删除
eureka.instance.lease-expiration-duration-in-seconds=15

## 配置定时获取|抓取注册中心的数据时间
eureka.client.registry-fetch-interval-seconds= 5
eureka.client.instance-info-replication-interval-seconds= 5
## 配置集群中其他eureka实例,用于本eureka实例的注册方。
eureka.client.region=beijing
eureka.client.availability-zones.beijing=zone-1,zone-2
eureka.client.service-url.zone-1=http://CentOSA:1111/eureka/
eureka.client.service-url.zone-2=http://CentOSB:1111/eureka/

2.4 部署 eurek

  • 上传eurekacloud-1.0-SNAPSHOT.jar到CentOSA、CentOSB、CentOSC
[root@CentOSA ~]# nohup java -jar BigData_day47_SpringCloud_Eureka1-1.0-SNAPSHOT.jar --spring.profiles.active=eureka-1  > log.file  2>&1 &
[root@CentOSB ~]# nohup java -jar BigData_day47_SpringCloud_Eureka1-1.0-SNAPSHOT.jar --spring.profiles.active=eureka-2  > log.file  2>&1 &
[root@CentOSC ~]# nohup java -jar BigData_day47_SpringCloud_Eureka1-1.0-SNAPSHOT.jar --spring.profiles.active=eureka-3 > log.file  2>&1 &

  • 访问浏览器查看Eureka是否启动成功
    在这里插入图片描述

2.5 Eureka自我保护机制

	由于Eureka再设计上遵循AP原则,一旦Eureka服务节点检测到异
		常Renews < Renews threshold(心跳阈值< 接收心跳)Eureka会进入
		自我保护机制。一旦进入自我保护机制,Eureka就会失去剔除失效节
		点功能(失去检测功能)。
	Renews threshold: 
	eureka.server.renewal-percent-threshold= 0.85
	集群: (2 x n) x eureka.server.renewal-percent-threshold 
			=  (2 * 3) *0.85 = 5.1     =5
	单机: 2 × (n+1) × eureka.server.renewal-percent-threshold 
			=  4 * 0.85  = 3.43
	默认自我保护机制是开启的(推荐选项)
	eureka.server.enable-self-preservation=true
	
	如果是单机模式很容易触发自我保护,因为
	Renews threshold= 21+10.85 = 3
	Renews (last min) 
		=60 / eureka.instance.lease-renewal-interval-in-seconds=30)* 1 = 2
	所以如果构建的是单机版本的Eureka,建议关闭自我保护机制。

2.6 发布服务

  • 依赖
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  • application.peroperties
	# 发布服务
	spring.application.name=USER-SERVICE
	# 发布服务实例id
	eureka.instance.instance-id=001 
	eureka.instance.prefer-ip-address=true
	eureka.instance.lease-renewal-interval-in-seconds=10
	eureka.instance.lease-expiration-duration-in-seconds=20
	
	# 只单纯的注册服务,并不获取服务注册列表信息
	eureka.client.register-with-eureka=true
	eureka.client.healthcheck.enabled=true
	eureka.client.fetch-registry=false
	eureka.client.service-url.defaultZone=http://CentOSA:1111/eureka/,http://CentOSB:1111/eureka/,http://CentOSC:1111/eureka/
  • Controller
@RestController// @Controller + @ResponseBody
@RequestMapping(value = "/FormUserManager")
public class FormUserController {
    //注入Service的实现类
    @Autowired
    private IUserService userService;
    
    @GetMapping("/queryById")
    @ResponseBody
    public User queryById(@RequestParam(value = "id") Integer id) {
        User user1 = userService.queryById(id);
        System.out.println(user1);
        return user1;
    }
}

2.7 引用服务

  • 依赖
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<!--引入 eureka后,无需再次引入Ribbon-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  • application.peroperties
	# 只是单纯的获取注册中心的注册信息,并不注册自己
	eureka.client.register-with-eureka=false
	eureka.client.fetch-registry=true
	eureka.client.service-url.defaultZone=http://CentOSA:1111/eureka/,http://CentOSB:1111/eureka/,http://CentOSC:1111/eureka/
  • controller
/**
 * (1)、从Euureka 中获取 注册的可用的服务。
 * (2)、Eureka 自动剔除失效的服务。
 */
@RestController
@RequestMapping(value = "/usermanager")
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping(value = "/queryUserById")
    public User queryUserById(@RequestParam(value = "id") Integer id){
        String url="http://USER-SERVICE/FormUserManager/queryById?id={id}";
        return restTemplate.getForObject(url,User.class,id);
    }
}

五 Hystrix (熔断器)

5.1 基本使用

  • Hystrix是一个延迟和容错库,旨在隔离对远程系统,服务和第三方库的访问点,停止级联故障。
  • pom.xml
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
</dependencies>
  • 在需要熔断的方法是添加@HystrixComand注解
@Service
public class UserService implements IUserService {
    //会产生代理,有这个注解。容错的方法。
    //https://blog.csdn.net/tongtong_use/article/details/78611225  配置参考。
    @HystrixCommand(
            fallbackMethod = "failback4Sum",
             //ignoreExceptions = {ArithmeticException.class},//忽略某个异常,不进行处理。
            commandProperties = {  //执行器执行隔离级别。2种
                            @HystrixProperty(name="execution.isolation.strategy",value="SEMAPHORE"),              @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "150")
            }
    )


    @Override
    public Integer sum(Integer x, Integer y) {
        try {
            int ms=new Random().nextInt(200);
            System.out.println("sleep:"+ms);
            System.out.println("ServiceThread:"+Thread.currentThread().getId());
            Thread.sleep(ms);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return (x+y)*2;
    }

    //容错方法。及捕获异常。必须放在最后。
    public Integer failback4Sum(Integer x, Integer y,Throwable  e) {
        return x+y+1;
    }
}
  • 在启动类上添加@EnableCircuitBreaker
@SpringBootApplication
@EnableCircuitBreaker//熔断器生效
public class HystrixSpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(HystrixSpringBootApplication.class,args);
    }
}
  • 线程隔离
  • 默认该方法的执行会启动新的线程执行和主程序不在一个线程中,因此如果上下文中存在ThreadLocal变量,在该方法中就失效了。因此一般可以通过设置commandProperties注解属性,设置线程就可以了。
  • execution.isolation.strategy该属性的可选值有两个THREAD和SEMAPHORE默认值是THREAD.①一般如果一个实例一秒钟有100个并发,此时因为频繁启动线程的开销过大此时一般考虑使用SEMAPHORE,②非网络调用。
@HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.strategy",value = "SEMAPHORE")
    })
@Override
public User queryUserById(Integer id) {
    System.out.println(Thread.currentThread().getId());
    return userDAO.queryById(id);
}
  • Fallback
  • 过在@HystrixCommand中声明fallbackMethod的名称可以实现优雅降级,如下所示:
  • 注意要求fallbackMethod方法和目标方法必须在同一个类中,具有相同的参数(异常参数可选)
@HystrixCommand(
    fallbackMethod = "failback4Sum",
    // ignoreExceptions = {ArithmeticException.class},
    commandProperties = {
        @HystrixProperty(name="execution.isolation.strategy",value="SEMAPHORE")
    }
)
@Override
public Integer sum(Integer x, Integer y) {
    System.out.println("thread:"+Thread.currentThread().getId());
    int b=10/0;
    return (x+y)*2;
}
public Integer failback4Sum(Integer x, Integer y,Throwable  e) {
    System.out.println(e.getMessage());
    return x+y;
}
  • 超时熔断
  • 用户可以通过设置execution.isolation.thread.timeoutInMilliseconds属性设置一个方法最大请求延迟,系统会抛出HystrixTimeoutException
@HystrixCommand(
    fallbackMethod = "failback4Sum",
    commandProperties = {
        @HystrixProperty(name="execution.isolation.strategy",value="THREAD"),
        @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "100")
    }
)
@Override
public Integer sum(Integer x, Integer y) {
    try {
        int ms=new Random().nextInt(200);
        System.out.println("sleep:"+ms);
        Thread.sleep(ms);
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    return (x+y)*2;
}
public Integer failback4Sum(Integer x, Integer y,Throwable  e) {
    return x+y;
}

5.2 熔断器限流

  • hystrix dashbord(监测)
# 开启健康检查的所有访问接口
management.endpoints.web.exposure.include=*
	@SpringBootApplication
	@EnableCircuitBreaker
	@EnableHystrixDashboard
	public class HystrixSpringBootApplication {
	    public static void main(String[] args) {
	        SpringApplication.run(HystrixSpringBootApplication.class,args);
	    }
	}
  • 完整熔断器配置
@Service
public class UserService implements IUserService {
    @HystrixCommand(
            fallbackMethod = "failback4QueryUserById",//容错,降级的处理。
            commandProperties = {
     //1000 毫秒有返回值,否者降处理。
     @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
     @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),

     // 时间窗口 必须是 numBuckets的整数倍数
     @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000"),//设置窗口长度10秒
     @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),//设置窗口滑动间隔1s

     //闸刀开启的条件 请求数> 10 && 错误率> 50%
       @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//设置最小请求次数
     @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),//设置错误率50%
     @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"),// 当全开到半开的时间间隔
            },
     //处理请求的数 最大为 线程的 个数加等待队列。
     threadPoolProperties = {
      @HystrixProperty(name = "coreSize", value = "2"),//设置线程池大小,默认10
       @HystrixProperty(name = "queueSizeRejectionThreshold", value = "2")//设置队列最大等待请求数
            }
    )

    @Override
    public User queryUserById(Integer id) {
        int random = new Random().nextInt(2500);
        try {
            System.out.println("sleep:" + random);
            Thread.sleep(random);
        } catch (InterruptedException e) {

        }
        return new User(id, "user" + id);
    }

    public User failback4QueryUserById(Integer id) {
        return new User(-1, "服务降级!");
    }
}
  • 访问 http://localhost:9999/hystrix 输入 http://localhost:9999/actuator/hystrix.stream进行监控。
  • http://localhost:9999/actuator–>http://localhost:9999/actuator/hystrix.stream
    *在这里插入图片描述
    在这里插入图片描述

六 OpenFeign

  • Feign是一个声明性的Web服务客户端。它使编写Web服务客户端变得更容易。
  • Feign 增加了对Spring MVC注解的支持,并使用了Spring MVC中相同HttpMessageConverters。
  • Feign集成了Ribbon、Eureka、Hystrix,在使用Feign时提供负载均衡以及容错的的http客户端。

6.1 application.properties

	server.port=9999
	# 配置Eureka 拦截参数
	eureka.client.register-with-eureka=false
	eureka.client.fetch-registry=true
	eureka.client.healthcheck.enabled=true
	eureka.client.service-url.defaultZone=http://CentOSA:1111/eureka/,http://CentOSB:1111/eureka/,http://CentOSC:1111/eureka/

6.2 UserFeignControllerClient

@FeignClient(name = "USER-SERVICE",fallback = UserFeignControllerFailBack.class)
public interface UserFeignControllerClient {
    //增、删、改、查
    @PostMapping(value = "/FormUserManager/registUser")
    @ResponseBody
    public void registUser(User user) throws IOException;

    @DeleteMapping(value = "/FormUserManager/deleteByIds")
    @ResponseBody
    public void deleteByIds(@RequestParam(value = "ids") Integer[] ids);

    @PutMapping(value = "/FormUserManager/updateUser")
    @ResponseBody
    public void updateUser(User user) throws IOException;
    
    @GetMapping(value = "/FormUserManager/queryById")
    @ResponseBody
    public User queryById(@RequestParam(value = "id") Integer id);

}

6.3 UserFeignControllerFailBack

/**
 * @param : 容错的实现
 */
@Component
public class UserFeignControllerFailBack implements UserFeignControllerClient {

    @Override
    public void registUser(User user) throws IOException {

    }

    @Override
    public void deleteByIds(Integer[] ids) {

    }

    @Override
    public void updateUser(User user) throws IOException {

    }

    @Override
    public User queryById(Integer id) {
        User user = new User(10,"故障",false, "***", new Date(), "xxxx");
        user.setId(id);
        return user;
    }
}

6.4 FeignSpringBootApplication

/**
 * @param :Feign集成了Ribbon、Eureka、Hystrix,
 *         在使用Feign时提供负载均衡以及容错的的http客户端。
 */
@SpringBootApplication
@EnableFeignClients
@EnableHystrixDashboard
@EnableCircuitBreaker
public class FeignSpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignSpringBootApplication.class, args);
    }

    //配置全局的Hystrix熔断属性
    @Bean
    public SetterFactory setterFactory() {
        return new SetterFactory() {
            @Override
            public HystrixCommand.Setter create(Target<?> target, Method method) {
                String groupKey = target.name();
                String commandKey = Feign.configKey(target.type(), method);

                HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
                        //设置统计指标10秒为一个时间窗口 一秒 滑动一次
                        .withMetricsRollingStatisticalWindowInMilliseconds(10000)
                        .withMetricsRollingPercentileBucketSize(10)
                        //操过50%失败率
                        .withCircuitBreakerErrorThresholdPercentage(50)
                        .withCircuitBreakerRequestVolumeThreshold(3)
                        .withCircuitBreakerSleepWindowInMilliseconds(5000)//半开状态时间
                        // 设置线程隔离
                        .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
                        //设置超时时间
                        .withExecutionTimeoutInMilliseconds(2000);

                return HystrixCommand.Setter
                        .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
                        .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
                        .andCommandPropertiesDefaults(setter);
            }
        };
    }
}

七 集中配置

7.1 配置服务器

作用:
 	为分布式系统中的基础设施和微服务应用提供集中化的外部配置支持。
配置服务端:
	它是一个独立的微服务应用, 用来连接配置仓库并为客户端提供获取配置信
	息、加密/解密信息等
客户端:
	是各个微服务应用的基础设施,通过指定的配置中心来管理应用资源与业务相关
	的配置内容,并在启动的时候从配置中心获取和加载配置信息。

在这里插入图片描述

7.2 服务端

  • SpringBootConfigServer
@SpringBootApplication
@EnableConfigServer
public class SpringBootConfigServer {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootConfigServer.class,args);
    }
}
  • application.properties
server.port = 8989
# 连接远程git读取配置信息
#spring.cloud.config.server.git.uri = file:///E:/config
spring.cloud.config.server.git.uri = https://github.com/sxyh/config.git

spring.cloud.config.server.git.repos.aa.search-paths=dir1
spring.cloud.config.server.git.repos.aa.clone-on-start=true
spring.cloud.config.server.git.repos.aa.pattern=app*
spring.cloud.config.server.git.repos.aa.uri= https://github.com/sxyh/config.git
spring.cloud.config.server.git.repos.aa.refresh-rate=5

management.endpoints.web.exposure.include=*

spring.application.name=CONFIG-SERVICE
eureka.instance.instance-id=001
eureka.instance.prefer-ip-address=true
eureka.instance.lease-expiration-duration-in-seconds=20
eureka.instance.lease-renewal-interval-in-seconds=10

eureka.client.register-with-eureka=true
eureka.client.healthcheck.enabled=true
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://CentOSA:1111/eureka/,http://CentOSB:1111/eureka/,http://CentOSC:1111/eureka/

7.3 客户端

  • ConfigClientApplication
@SpringBootApplication
public class ConfigClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigClientApplication.class,args);
    }
}
  • application.properties
	server.servlet.context-path= /SpringCloudConfigClient
  • bootstrap.properties
	# 指定连接的配置服务名字
	spring.application.name=aa
	
	spring.cloud.config.profile=test
	spring.cloud.config.label=master
	spring.cloud.config.name= SpringCloudConfigServer
	
	spring.cloud.config.discovery.enabled=true
	spring.cloud.config.discovery.service-id=CONFIG-SERVICE
	
	#spring.cloud.config.uri=http://localhost:8989
	
	eureka.client.register-with-eureka=false
	eureka.client.fetch-registry=true
	eureka.client.service-url.defaultZone=http://CentOSA:1111/eureka/,http://CentOSB:1111/eureka/,http://CentOSC:1111/eureka/
	
	# 开启所有的健康检查
	management.endpoints.web.exposure.include=*

八 Spring Cloud Bus

  • 消息总线:轻量级的消息代理,通过构建一个共用的消息主题,让系统中所有微服务实例都连接上来,该主题中产生的消息会被所有实例监听和消费。
  • 消息总线上的各个实例都可以方便地广播一些需要让其他连接在该主题上的实例都知道的消息。
  • 使用 Spring Cloud Bus, 可以非常容易地搭建起消息总线, 同时实现了一些消息总线中的常用功能, 比如, 配合Spring Cloud Config 实现微服务应用配置信息的动态更新等。
    在这里插入图片描述
  • pom依赖
	<dependency>
	    <groupId>org.springframework.cloud</groupId>
	    <artifactId>spring-cloud-starter-bus-kafka</artifactId>
	</dependency>
	<dependency>
	    <groupId>org.springframework.cloud</groupId>
	    <artifactId>spring-cloud-bus</artifactId>
	</dependency>
  • 在配置文件中添加消息总线配置
spring.kafka.bootstrap-servers=CentOSA:9092,CentOSB:9092,CentOSC:9092

	#前提
	启动 kafak 服务
	/usr/zookeeper-3.4.6/bin/zkServer.sh start zoo.cfg
	/usr/zookeeper-3.4.6/bin/zkServer.sh status zoo.cfg

在这里插入图片描述

  • 发布更新服务
    在这里插入图片描述
    在这里插入图片描述
  • 注意:所有的客户端节点都可以执行 消息的 总线的发布和订阅信息。其中aa:9090中aa表示刷新的应用名,9090表示刷新服务的端口。也可在纤细总执行刷新。

九、 Spring Cloud Zuul 路由(反向代理)

  • 路由是微服务架构不可或缺的一部分。例如/可能映射到您的Web应用程序,/api/users映射到用户服务,/api/shop映射到商店服务。 Zuul是Netflix的基于JVM的路由器和服务器端负载均衡器。
    在这里插入图片描述
    *application.properties
server.port=9999

zuul.routes.users.path=/users/**
zuul.routes.users.service-id=USER-SERVICE
zuul.routes.users.sensitive-headers=

# 配置USER-SERVICE熔断属性
hystrix.command.USER-SERVICE.execution.isolation.strategy=THREAD
hystrix.command.USER-SERVICE.execution.isolation.thread.timeoutInMilliseconds=10000

USER-SERVICE.ribbon.ConnectTimeout=1000
USER-SERVICE.ribbon.ReadTimeout=1000

#尝试其他服务器一次,#最大尝试次数
USER-SERVICE.ribbon.MaxAutoRetriesNextServer=1
USER-SERVICE.ribbon.MaxAutoRetries=2

#开启容错策略重试
zuul.retryable=true

management.endpoints.web.exposure.include=*

# 配置Eureka
eureka.instance.appname=ZUUL-EUREKA
eureka.instance.instance-id=001
eureka.instance.prefer-ip-address=true
eureka.instance.lease-expiration-duration-in-seconds=20
eureka.instance.lease-renewal-interval-in-seconds=10

eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
eureka.client.healthcheck.enabled=true
eureka.client.service-url.defaultZone=http://CentOSA:1111/eureka/,http://CentOSB:1111/eureka/,http://CentOSC:1111/eureka/

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值