SpringCloud基础(1)

目录:
SpringCloud基础(0)
SpringCloud基础(1)
SpringCloud基础(2)
SpringCloud基础(3)
SpringCloud基础(4)
SpringCloud基础(5)

1 服务注册中心、提供者和消费者

1.1 创建服务注册中心

创建一个maven工程,在pom.xml中引入依赖的内容:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.3.5.RELEASE</version>
</parent>

<dependencyManagement>
  <dependencies>
      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-dependencies</artifactId>
          <version>Brixton.RELEASE</version>
          <type>pom</type>
          <scope>import</scope>
      </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
  </dependency>

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

</dependencies> 

在顶层包下创建application类,开启@EnableEurekaServer注解。

@EnableEurekaServer
@SpringBootApplication
public class Application {
	public static void main(String[] args) {
		new SpringApplicationBuilder(Application.class).web(true).run(args);
	}
}

默认情况下该服务注册中心会将自己也作为客户端来尝试注册自己,所以需要禁用自身的注册,只需要在application.propertis中增加如下配置:

server.port=1111
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/

运行Application中的main方法,访问http://localhost:1111/即可看到eureka的默认页面,暂时还没有任何服务。

1.2 创建服务提供者

下面创建服务提供者,并向服务注册中心注册自己。另外创建一个Maven工程,引入依赖:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.5.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Brixton.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

假设我们有一个提供计算功能的微服务模块,我们实现一个restful API,通过传入两个参数a和b,最后返回a+b的结果:

@RestController
public class ComputeController {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private DiscoveryClient client;
    @RequestMapping(value = "/add" ,method = RequestMethod.GET)
    public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
        ServiceInstance instance = client.getLocalServiceInstance();
        Integer r = a + b;
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
        return r;
    }
}

最后在主类中开启@EnableDiscoveryClient注解,使服务能够去注册中心注册。

@EnableDiscoveryClient
@SpringBootApplication
public class ComputeServiceApplication {
	public static void main(String[] args) {
		new SpringApplicationBuilder(ComputeServiceApplication.class).web(true).run(args);
	}
}

在application.properties中添加服务名和服务提供者的端口,并配置服务注册中心。

spring.application.name=compute-service
server.port=2222
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

分别运行服务注册中心和服务提供者,访问http://localhost:1111/,就能看到提供的compute-service服务了。

1.3 创建服务消费者

Ribbon是一个基于HTTP和TCP客户端的负载均衡器,可以在通过客户端中配置的ribbonServiceList服务端列表去轮询访问达到负载均衡的作用。

当Ribbon和Eureka联合使用时,ribbonServerList会被DiscoveryNIWSServerList重写,扩展成从Eureka注册中心中获取服务端列表。同时它会用NIWSDiscoveryPing来取代IPing,它将职责委托给Eureka来确定服务端是否已经启动。

下面通过实例来使用Ribbon调度服务,实现客户端的负载均衡。

客户端负载均衡和服务端负载均衡最大的不同在于服务清单所存储的位置。服务端负载均衡如nginx,将服务清单维护在服务端。而在客户端负载均衡中,所有的客户端节点都要维护自己要访问的服务端清单,而这些服务端清单来自于服务注册中心。

复制一个服务提供者,将其服务端口改为2223(实际中一般是在不同的服务器上部署多个相同的微服务),分别启动服务注册中心和两个服务提供者。
访问http://localhost:1111/,就能看到提供的compute-service服务有两个提供者。
接着创建一个maven工程,在pom.xml中加入依赖:

<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>1.3.5.RELEASE</version>
</parent>
<dependencies>
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-ribbon</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-eureka</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-test</artifactId>
       <scope>test</scope>
   </dependency>
</dependencies>
<dependencyManagement>
   <dependencies>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-dependencies</artifactId>
           <version>Brixton.RELEASE</version>
           <type>pom</type>
           <scope>import</scope>
       </dependency>
   </dependencies>
</dependencyManagement>

在应用主类中,通过@EnableDiscoveryClient注解来自动注册。创建RestTemplate实例,并通过@LoadBalanced注解开启均衡负载能力。

@SpringBootApplication
@EnableDiscoveryClient
public class RibbonApplication {
	@Bean
	@LoadBalanced
	RestTemplate restTemplate() {
		return new RestTemplate();
	}
	public static void main(String[] args) {
		SpringApplication.run(RibbonApplication.class, args);
	}
}

创建ConsumerController来消费COMPUTE-SERVICE的add服务。通过直接RestTemplate来调用服务,计算10 + 20的值。

@RestController
public class ConsumerController {
    @Autowired
    RestTemplate restTemplate;
    
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add() {
        return restTemplate.getForEntity("http://COMPUTE-SERVICE/add?a=10&b=20", String.class).getBody();
    }
}

配置服务注册中心和消费者名称和端口:

spring.application.name=ribbon-consumer
server.port=3333
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

当服务注册中心,服务提供者和消费者都启动之后,多次访问http://localhost:3333/add,查看服务提供者的控制台输出信息,会发现服务请求轮流被分配给两个服务提供者。

可以看到,使用Spring Cloud Ribbon负载均衡非常简单,只需要两步:

1.服务端启动多个实例,并注册到服务注册中心;
2. 消费者通过调用被@LoadBalanced注解修饰过的RestTemplate来实现面向服务的接口调用。

具体执行过程见ribbon原理

以上服务消费者使用Ribbon作为负载均衡器,也可以使用Feign作为负载均衡器。

Feign是一个声明式的web服务客户端,它使得编写web服务客户端变得更加简单,只需要使用Feign来创建一个接口并用注解来配置它即可完成。具备可插拔的注解支持,包括Feign注解和JAX-RS注解。Feign也支持可插拔的编码器和解码器。

Spring Cloud为Feign增加了对Spring MVC注解的支持,还整合了Ribbon和Eureka来提供均衡负载的HTTP客户端实现。

下面通过实例来使用Feign调度compute-service服务。

新建一个maven工程,引入依赖:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Brixton.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>

在主类中开启@EnableFeignClients注解:

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

然后定义compute-service服务接口:

@FeignClient("compute-service")
public interface ComputeClient {
    @RequestMapping(method = RequestMethod.GET, value = "/add")
    Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b);
}

系统会自动将compute-service服务绑定为该接口的实现。
实现调用接口:

@RestController
public class ConsumerController {
    @Autowired
    ComputeClient computeClient;
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public Integer add() {
        return computeClient.add(10, 20);
    }
}

配置消费者名称,端口和服务注册中心

spring.application.name=feign-consumer
server.port=5555
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

启动新增的消费者后,多次访问http://localhost:5555/add,会发现服务请求轮流被两个服务提供者处理。

1.4 高可用服务注册中心

前文介绍过Eureka服务注册中心,但这个服务注册中心是单点的,即只有一个实例。在实际项目中,一般服务注册中心都是集群形式的,防止单个服务注册中心宕掉之后导致服务无法注册。

Eureka Server可以通过运行多个实例,并进行互相注册的方式来实现高可用的部署,所以只需要将Eureka server配置其他可用的serviceUrl就能实现高可用部署。

以前文的服务注册中心为蓝本复制一个服务注册中心,名称为mysc-server2。

修改两个注册中的配置文件,注册中心1为:

spring.application.name=eureka-server
server.port=1111
eureka.instance.hostname=peer1
eureka.client.serviceUrl.defaultZone=http://peer2:1112/eureka/

注册中心2为:

spring.application.name=eureka-server
server.port=1112
eureka.instance.hostname=peer2
eureka.client.serviceUrl.defaultZone=http://peer1:1111/eureka/

两个注册中心互相注册。
在hosts文件中加入peer1和peer2的解析,都映射到127.0.0.1:

127.0.0.1 peer1
127.0.0.1 peer2

分别启动两个注册中心,先启动的注册中心由于找不到其要注册的地址会报错,但是当另一个注册中心启动完成之后就好了。

此时访问peer1的注册中心:http://localhost:1111/,如下图所示,我们可以看到registered-replicas中已经有peer2节点的eureka-server了。同样地,访问peer2的注册中心:http://localhost:1112/,能看到registered-replicas中已经有peer1节点,并且这些节点在可用分片(available-replicase)之中。我们也可以尝试关闭peer1,刷新http://localhost:1112/,可以看到peer1的节点变为了不可用分片(unavailable-replicas)。

现在将服务提供者provider1的配置文件中的注册中心地址改为:

eureka.client.serviceUrl.defaultZone=http://peer1:1111/eureka/,http://peer2:1112/eureka/

这样该服务就会在两个注册中心实例上都注册了,即使其中一个注册中心宕机,另外一个仍然能保证服务注册与发现正常工作。

这里以双节点作为例子,实际项目中因为负载等原因,往往可能需要构建多个注册中心实例。如何配置serviceUrl来让集群中的服务进行同步,需要理解Eureka的同步机制。

Eureka Server的同步遵循一个非常简单的原则:只要有一条边将节点连接,就可以进行信息传播与同步。看一个场景:

假设有三个注册中心peer1,peer2和peer3,各自将serviceUrl指向另外两个节点。启动三个注册中心,并将computer-service的serviceUrl指向peer1并启动。访问http://localhost:1112/,可以看到三个注册中心组成了集群,compute-service服务通过peer1同步给了peer2和peer3。即是说,尽管只向其中一个注册中心注册了服务,但实际上所有注册中心上都拥有该服务,注册中心的节点会向整个注册中心集群传播服务提供者。因此可以得出一个结论:两两注册的方式可以实现集群中节点完全对等的效果,实现最高可用性集群,任何一台注册中心故障都不会影响服务的注册与发现

参考资料

[1]http://bbs.springcloud.com.cn/d/1-dd-spring-cloud

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值