一、Spring Cloud简介

1.1 什么是Spring Cloud
Spring Cloud是在SpringBoot的基础上构建的,用于简化分布式系统构建的工具集。该工具集为微服务架构中所涉及得到配置管理、服务发现、智能路由、断路器、微代理和控制总线等操作提供了一种简单的开发方式。
1.2 Spring Cloud的特点
SpringCloud有很多特点,其中最大的特点就是它的集成性,它将很多开源产品都继承到了自身的框架中,使其越来越强大。除此之外,Spring Cloud还有如下特点:

  • 1、使用方便
  • 2、功能齐全
  • 3、易于扩展和维护
        所有组件都通过引入的方式,通过Maven或Gradle引入依赖。各个组件之间没有代码上的耦合,因此可以根据需求不断的增加、删除和替换组件。
  • 4、适用于各种环境
    使用Spring Cloud组件开发的项目可以应用于PC服务器、云环境,以及各种容器(Docker)。

二、服务发现

2.1 Eureka介绍
   Eureka是Netfix开发的一个服务发现框架,本身是一个基于REST的服务,主要用于定位运行在AWS(Amazon Web Services)域的中间层服务,以达到负载均衡和中间层服务故障转移的目的。Spring Cloud将其集成在自己的子项目Spring Cloud Netflix中,以实现spring Cloud服务发现功能。
Eureka的服务包含两大组件:服务端发现组件(Eureka Server)和客户端发现组件(Eureka Client)。服务端发现组件也被称之为服务注册中心,主要提供了服务注册功能。
2.2 使用Eureka服务
1、搭建Maven父工程
在Eclipse中,创建一个Maven父工程microservice-springcloud,并在工程的pom.xml中添加Spring Cloud的版本依赖等信息,

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.spring</groupId>
  <artifactId>microservice-springcloud</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>
  <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.20.RELEASE</version>
      <relativePath/>
  </parent>
  <properties>
      <project.build.sourceEncoding>
          UTF-8
      </project.build.sourceEncoding>
      <project.reporting.outputEncoding>
          UTF-8
      </project.reporting.outputEncoding>
      <java.version>1.8</java.version>
  </properties>
 <dependencyManagement>  //Dalston SR3版本的依赖配置
      <dependencies>
          <dependency>
              <groupId>org.springframework.cloud</groupId>
              <artifactId>spring-cloud-dependencies</artifactId>
              <version>Dalston.SR3</version>
              <type>pom</type>
              <scope>import</scope>
          </dependency>
      </dependencies>
  </dependencyManagement>
  <build>
      <plugins>
          <!-- Spring Boot的编译插件 -->
          <plugin>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
      </plugins>
      </build>
  <modules>
  	<module>microservice-eureka-server</module>
  	<module>microservice-eureka-user</module>
    <module>microservice-eureka-order</module>
  </modules>
</project>

2、搭建服务端工程
在父工程microservice-springcloud中,创建Maven子模块microservice-eureka-server作为服务端工程,该模块是一个基础的Spring Boot工程,其主要代码实现过程如下。
(1)添加依赖。在Pom.xml中添加Eureka Server的依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>cloud</groupId>
    <artifactId>cloud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>microservice-eureka-server</artifactId>
  <dependencies>
     <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-eureka-server</artifactId>
     </dependency>
  </dependencies>
</project>

(2)编写配置文件。在配置文件中增加端口号等配置信息,如文件中怎能更加端口号等配置信息。
application.yml

server:
  port: 8761
eureka:
  instance:
    hostname: localhost
  server:
    enable-self-preservation: false 
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
       defaultZone:
               http://${eureka.instance.hostname}:${server.port}/eureka/

(3)修改服务端代码,在项目的引导类上添加注解@EnableEurekaServer,该注解用于声明标注类是一个Eureka Server。
Application.java

package com.itheima.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
   public static void main(String args[])
   {
	   SpringApplication.run(EurekaApplication.class, args);
   }
}

(4)启动应用,查看信息,完成上述配置以后,启动应用程序并在浏览器中访问地址http://localhost:8761即可看到Eureka的信息面板,

Spring Cloud Circuit Breaker 全局启用_Eureka


Spring Cloud Circuit Breaker 全局启用_xml_02


3、搭建客户端工程

在父工程microservice-springcloud中,创建Maven子模块microservice-eureka-user作为客户端工程,该模块是一个基础的Spring Boot工程,其主要代码实现过程如下。

(1)添加依赖,在pom.xml中添加Eureka依赖,

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>cloud</groupId>
    <artifactId>cloud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>microservice-eureka-user</artifactId>
   <dependencies>
     <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-eureka</artifactId>
     </dependency>
  </dependencies>
</project>

(2)编写配置文件,在配置文件中添加Eureka服务实例的端口号,服务端地址等信息。
application.yml

server:
  port: 8000  #指定该Eureka实例的端口号
eureka:
  instance:
    prefer-ip-address: true  #是否显示主机的ip
  client:
    service-url:
       defaultZone:
               http://localhost:8761/eureka/  #指定Eureka服务端地址
spring:
   application:
      name: microservice-eureka-user  # 指定应用名称

(3)修改客户端代码。在项目的引导类上添加注解@EnableEurekaClient,该注解用于声明标注类是一个Eureka客户端组件,
Application.ava

package com.itheima.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@RestController
public class Application {
	@RequestMapping("/hello")
    public String home()
    {
    	return "hello world!";
    }
    public static void main(String args[])
    {
    	SpringApplication.run(Application.class, args);
    } 
}

(4)启动应用,查看信息。完成上述配置后,分别启动服务器工程和客户端工程,在浏览器中访问http://localhost:8761/后,我们可以从Eureka的信息面板中看到注册的服务信息。

Spring Cloud Circuit Breaker 全局启用_Spring Cloud_03


从上图可以看出,服务已成功注册到了注册中心,注册后的服务就可以直接被其他服务调用了。

需要注意的是,在注册信息页面中出现红色警告信息。

出现警告信息是本地调试时触发了Eureka Server的自我保护机制,会使注册中心所维护的实例不是很准确,所以在本地开发时,可以在Eureka-servery应用的配置文件中使用eureka.server.enable-self-preservation=false参数来关闭保护机制。
2.3 如何实现服务间的调用
1、搭建订单服务工程
在父工程microservice-springcloud中,创建Maven子模块microservice-eureka-order作为客户端工程,其主要代码实现过程如下。
(1)在pom.xml中,添加spring-cloud-starter-eureka依赖。

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

(2)编写配置文件,在配置文件中添加Eureka服务实例的端口号,服务端地址等信息。
application.yml

server:
  port: 7900  # 指定该Eureka实例的端口号
eureka:
  instance:
    prefer-ip-address: true  # 是否显示主机的ip
  client:
    service-url:
       defaultZone:
               http://localhost:8761/eureka/  # 指定Eureka服务端地址
spring:
   application:
      name: microservice-eureka-order # 指定应用名称

(3)创建订单实体类。创建com.itheima.springcloud.po包,并在包中创建订单实体类Order,
Order.java

package com.itheima.springcloud.po;

public class Order {
    private String id;
    private Double price;
    private String receiverName;
    private String receiverAddress;
    private String receiverPhone;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public Double getPrice() {
		return price;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
	public String getReceiverName() {
		return receiverName;
	}
	public void setReceiverName(String receiverName) {
		this.receiverName = receiverName;
	}
	public String getReceiverAddress() {
		return receiverAddress;
	}
	public void setReceiverAddress(String receiverAddress) {
		this.receiverAddress = receiverAddress;
	}
	public String getReceiverPhone() {
		return receiverPhone;
	}
	public void setReceiverPhone(String receiverPhone) {
		this.receiverPhone = receiverPhone;
	}
	@Override
	public String toString() {
		return "Order [id=" + id + ", price=" + price + ", receiverName=" + receiverName + ", receiverAddress="
				+ receiverAddress + ", receiverPhone=" + receiverPhone + "]";
	}
}

(4)创建订单控制器类。创建com.itheima.springcloud.controller包,并在包中创建订单控制器类OrderController。在该类中模拟编写一个通过id查询订单的方法。
OrderController.java

package com.itheima.springcloud.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.itheima.springcloud.po.Order;
import com.itheima.springcloud.service.ServiceInfoUtil;
@RestController
public class OrderController {
	@GetMapping("/order/{id}")
    public String findOrderById(@PathVariable String id)
    {
		System.out.println(ServiceInfoUtil.getPort());
    	Order order = new Order();
    	order.setId("123");
    	order.setPrice(23.5);
    	order.setReceiverAddress("beijing");
    	order.setReceiverName("xioachen");
    	order.setReceiverPhone("666666666666");
    	return order.toString();	
    }
}

(5)在引导类中添加注解@EnableEurekaClient
2、编写用户服务功能
(1)在microservicce-eureka-user工程的引导类中,创建RestTemplate的Spring实例,其代码如下:

@Bean
    @LoadBalanced
	public RestTemplate restTemplate()
	{
	    return new RestTemplate();
	}

在上述代码中,RestTemplate是Spring提供的用于访问Rest服务的客户端实例,它提供了多种便捷访问远程Http服务的方法,可以提高客户端编写效率。
(2)创建用户控制器类,在类中编写查询方法。
UserController.java

package com.itheima.springcloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class UserController {
   @Autowired
   private RestTemplate restTemplate;
   /**
    *查询与用户相关的订单
    */
   @GetMapping("/findOrdersByUser/{id}")
   public String findOrdersByUser(@PathVariable String id)
   {
	   int oid = 123;
	   return this.restTemplate
			      .getForObject("http://microservice-eureka-order/order/" + oid, String.class );
   }
}

3、启动服务应用,测试服务调用

分别启动服务注册中心、订单服务应用和用户服务应用,此时Eureka信息页面的显示信息如图:

Spring Cloud Circuit Breaker 全局启用_spring_04