spring boot學習筆記(四):Spring Cloud

實例代碼:http://git.oschina.net/null_584_3382/spring-cloud-examplegit

spring boot結合docker技術,能夠構建微服務。特別是spring cloud的出現,爲咱們解決了分佈式開發經常使用遇到的問題。等配置管理,服務發現,斷路器,代理服務,負載均衡等spring

1.Spring Cloud簡介

1.1 配置服務

Spring Cloud提供了Config Server的解決方案,支持git和本地文件存放配置文件。使用@EnableConfigServer來啓動配置服務docker

1.2 服務發現

Spring Cloud 經過Netfix OSS的Eureka來實現服務發現。Eureka Server提供服務註冊bootstrap

其中服務端使用@EnableEurejaServer註解,客戶端使用@EnbaleEurekaClientapi

1.3 路由網關

Spring經過Zuul開實現,支持自動路由到在Eureka上註冊的俯臥,是同@EnbaleZuulProxy來啓動路由代理app

1.4 負載均衡

Spring Cloud提供了Ribbon和Feign做爲客戶端的負載均衡。使用起來都很方便,負載均衡

1.5 斷路器

斷路器是爲了解決某個方法調用失敗的時候,調用後備方法來替代失敗的方法。Spring Cloud使用@EnableCircuitBreaker來啓動斷路器支持。dom

2. Spring Cloud實例

parent pom文件分佈式

<modules>
        <module>discovery</module>
        <module>config</module>
        <module>service</module>
        <module>gateway</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
    </parent>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

2.1 服務發現

依賴:ide

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
    </dependency>
</dependencies>

主要代碼,就一個boot啓動類,加上@EnableEurekaServer註解

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

配置文件:因爲是單機環境,所以不須要註冊本身(若是是集羣服務就須要註冊本身和集羣其餘發現服務)

eureka:
  client:
    register-with-eureka: false  
    fetch-registry: false

2.2 配置服務

依賴:

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

代碼:@EnableConfigServer聲明是一個配置管理服務,因爲使用本地文件保存配置信息,須要在Erueka上註冊,所以須要@EnableEurekaClient

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

配置:

bootstrap.yml:

spring:
  application:
    name: config
  profiles:
    active: native #1
    
eureka:
  instance:
    non-secure-port: ${server.port:19882}
    metadata-map:
      instanceId: ${spring.application.name}:${random.value}   #2
  client:
    service-url:
      defaultZone: http://${eureka.host:localhost}:${eureka.port:19881}/eureka/  #3

#1 配置文件存在本地文件

#2 實例名字

#3 eureka地址

application.yml

spring:
  cloud:
    config:
      server:
        native:
          search-locations: classpath:/config #1

server:
  port: 19882

#1 配置文件存放的位置爲 classpath:/config下

文件存儲的規則爲

  • /{application}/{profile}/{label}
  • /{application}-{profile}.yml  or properties
  • /{label}/{application}-{profile}.yml  or properties

computer.yml 表示 application的名字爲computer 的服務(沒有profile)

在computer.yml裏面寫入

my:
  name: lizo

2.3 服務模塊

寫一個簡單的rest服務模塊,

啓動類:

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

controller:提供一個加法運算和一個獲取配置服務的rest api

@RestController
public class ComputerController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${my.name}")
    private String name;

    @RequestMapping("/add")
    public int add(@RequestParam("a") int a, @RequestParam("b") int b) {
        return a + b;
    }


    @RequestMapping("/name")
    public String name() {
        logger.info("########### call me!!!!!!");
        return name;
    }
}

bootstrap.yml

spring:
  application:
    name: computer
  cloud:
    config:
      enabled: true
      discovery:
        enabled: true
        service-id: CONFIG #1
eureka:
  instance:
    non-secure-port: ${server.port:19883}
  client:
    service-url:
      defaultZone: http://${eureka.host:localhost}:${eureka.port:19881}/eureka/

#1 從註冊的服務中獲取配置信息,配置服務註冊的名字爲CONFIG

2.4 網關

Controller:對外暴力的方法

@RestController
public class GatewayController {

    @Autowired
    ComputerFeignService computerFeignService;

    @RequestMapping("/getadd")
    public int getadd(@RequestParam("a") int a,@RequestParam("b") int b){
        return computerFeignService.add(a,b);
    }

    @RequestMapping("/getName")
    public String getName(){
        return computerFeignService.name();
    }
}

server:這裏使用feign做爲例子演示,

@FeignClient(value = "computer",fallback = ComputeClientHystrix.class)
public interface ComputerFeignService {
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    int add(@RequestParam("a") Integer a, @RequestParam("b") Integer b);

    @RequestMapping(value = "/name",method = RequestMethod.POST)
    String name();
}

value="computer"表示提供服務的application爲computer,fallback是熔斷器處理

@Component
public class ComputeClientHystrix implements ComputerFeignService{
    @Override
    public int add(@RequestParam("a") Integer a, @RequestParam("b") Integer b) {
        return -111919;
    }

    @Override
    public String name() {
        return "exception";
    }
}

bootstrap:仍是常規的 

spring:
  application:
    name: gateway

eureka:
  instance:
    non-secure-port: ${server.port:80}
  client:
    service-url:
      defaultZone: http://${eureka.host:localhost}:${eureka.port:19881}/eureka/

3 測試

依次啓動發現服務和配置服務,其餘的不分順序

1. 服務發現

輸入 http://localhost:19881/

發現其餘服務都註冊成功了

2.配置管理

輸入 http://localhost/getName

輸出 lizo 發現成功讀取了配置文件中的內容

3.熔斷

關掉computer服務 而後再訪問http://localhost/getName

輸出exception 說明熔斷器是發揮了做用的

4. 負載均衡

若是啓動2個computer服務,而後屢次調用http://localhost/getName,發現確實每次回調用其中一個,打日誌"########### call me!!!!!!" 說明負載均衡也是作了的

 

實例代碼:http://git.oschina.net/null_584_3382/spring-cloud-example

相關文章
相關標籤/搜索