Spring Cloud实战(六)-Spring Cloud Netflix Bus

概要

  • 什么是Spring Cloud Netflix Bus?

  • 怎么用 Spring Cloud Netflix Bus?

什么是Spring Cloud Netflix Hystrix?

Spring Cloud Netflix Bus是Spring Cloud的消息机制,当Git Repository 改变时,通过POST请求Config Server的/bus/refresh,Config Server 会从repository获取最新的信息并通过amqp传递给client,如图所示.

Spring Cloud Bus的更新只对三种情况有效

  1. @ConfigurationProperties

  2. @RefreshScope

  3. 日志级别

怎么用Spring Cloud Netflix Hystrix?

百说不如一run,构造一个例子来实现

  • 基于实战一的例子

  • 下载并运行rabbit

  • 在Config Server及client添加bus,actuator依赖

         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bus-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

@ConfigurationProperties 实现

  • 修改Config Client 的LuckyWordController,注意去掉@Value注解,和添加getter/setter

@RestController
@ConfigurationProperties(prefix = "wordConfig")
public class LuckyWordController {

    String luckyWord;

    @RequestMapping("/lucky-word")
    public String showLuckyWord() {
        return "The lucky word is: " + luckyWord;
    }

    public String getLuckyWord() {
        return luckyWord;
    }

    public void setLuckyWord(String luckyWord) {
        this.luckyWord = luckyWord;
    }
}

@RefreshScope 实现

@RestController
@RefreshScope
public class LuckyWordController {

    @Value("${wordConfig.luckyWord}")String luckyWord;
    
    @RequestMapping("/lucky-word")
    public String showLuckyWord() {
        return "The lucky word is: " + luckyWord;
    }
}
  • 修改git repository

wordConfig:
  luckyWord: mmb
wordConfig:
  luckyWord: mmb222

@ConfigurationProperties的改变时直接重新绑定@RefreshScope不仅仅是重新绑定,它是重新再绑定一个bean.@RefreshScope的工作原理Spring创建一个代理Proxy,Proxy中包含注入的依赖及调用目标bean的方法,当更新Refresh时,新Proxy就会指向改变的bean,而老的Proxy还指向老的bean.所以它更安全

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值