Spring Cloud 初识

简介:Spring Cloud是在Spring Boot的基础上构建的,用于简化分布式系统构建的工具集,为开发人员提供快速建立分布式系统中的一些常见的模式。

    例如:配置管理(configuration management),服务发现(service discovery),断路器(circuit breakers),智能路由( intelligent routing),

    微代理(micro-proxy),控制总线(control bus),一次性令牌( one-time tokens),全局锁(global locks),领导选举(leadership election),

    分布式会话(distributed sessions),集群状态(cluster state)。

Spring Cloud 包含了多个子项目:

   例如:Spring Cloud Config、Spring Cloud Netflix等

Spring Cloud 项目主页:http://projects.spring.io/spring-cloud/

关于服务发现

      在微服务架构中,服务发现(Service Discovery)是关键原则之一。手动配置每个客户端或某种形式的约定是很难做的,并且很脆弱。Spring Cloud提供了多种服务发现的实现方式,

例如:Eureka、Consul、Zookeeper。 Spring Cloud支持得最好的是Eureka,其次是Consul,最次是Zookeeper。

  • 在生产环境下,我们往往会为每个应用配置一个host,使用host而非IP进行访问。为了更加贴近生产环境,以及后文Docker章节的讲解,我们首先配置一下Host

代码示例

  • 创建一个Maven工程(microservice-discovery-eureka),并在pom.xml中加入如下内容:

 

<?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> <artifactId>microservice-discovery-eureka</artifactId> <packaging>jar</packaging> <parent> <groupId>com.itmuch.cloud</groupId> <artifactId>spring-cloud-microservice-study</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> </dependencies> </project> 
  • 编写Spring Boot启动程序:通过@EnableEurekaServer申明一个注册中心:
/**
 * 使用Eureka做服务发现。
 * @author eacdy
 */
@SpringBootApplication
@EnableEurekaServer public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } }
  • 在默认情况下,Eureka会将自己也作为客户端尝试注册,所以在单机模式下,我们需要禁止该行为,只需要在application.yml中如下配置:
server:
  port: 8761                    # 指定该Eureka实例的端口

eureka:  instance:  hostname: discovery # 指定该Eureka实例的主机名  client:  registerWithEureka: false  fetchRegistry: false  serviceUrl:  defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
# 参考文档:http://projects.spring.io/spring-cloud/docs/1.0.3/spring-cloud.html#_standalone_mode
# 参考文档:http://my.oschina.net/buwei/blog/618756

  启动工程后,访问:http://discovery:8761/ ,如下图。我们会发现此时还没有服务注册到Eureka上面。

Eureka启动界面

代码地址(任选其一)

http://git.oschina.net/itmuch/spring-cloud-study/tree/master/microservice-discovery-eureka

https://github.com/eacdy/spring-cloud-study/tree/master/microservice-discovery-eureka

 

猜你喜欢

转载自www.cnblogs.com/zhouy-77253569/p/9271933.html