SpringCloud整合了一套较为完整的微服务解决方案框架,而Dubbo只是解决了微服务的几个方面的问题。
content
Dubbo
SpringCloud
服务注册中心
zookeeper
Spring Cloud Netflix Eureka
服务调用方式
RPC
REST API
服务网关
无
Spring Cloud Netflix Zuul
断路器
不完善
Spring Cloud Netflix Hystrix
分布式配置
无
Spring Cloud Config
服务跟踪
无
Spring Cloud Sleuth
消息总线
无
Spring Cloud Bus
数据流
无
Spring Cloud Stream
批量任务
无
Spring Cloud Task
当然,虽然dubbo没有提供很多解决方案,但他也可以整合第三方的项目来实现。
今天介绍的服务发现是在SpringCloud的子项目Netflix中,除此之外,他还提供了熔断器、负载均衡、智能路由等,之后会介绍到。
和往常一样,我们先来实现这个实例,然后再分析。这里,我们需要一个服务注册中心(即下面例子中的eureka-server)和一个服务的提供方(eureka-provider)。
org.springframework.boot
spring-boot-starter-parent
1.4.0.RELEASE
UTF-8
1.8
org.springframework.cloud
spring-cloud-starter-eureka-server
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
Camden.SR3
pom
import
新建application.properties,注意名称只能是这个,不然不会被识别。
server.port=8761
#注册中心默认端口就是8761,也可通过下面的方式定义其他端口
#eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
@EnableEurekaServer //启动一个服务注册中心提供给其他应用进行对话
@SpringBootApplication
public class ServerApplication {
public static void main(String[] args) {
//下面两行代码都可以用来启动
SpringApplication.run(ServerApplication.class, args);
//new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
在浏览器中输入http://localhost:8761就会显示:
org.springframework.cloud
spring-cloud-starter-eureka
#应用(服务)名称
spring.application.name=compute-service
server.port=8762
#注册中心地址
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
Controller中,通过DiscoveryClient发现服务。
启动类
@EnableDiscoveryClient //激活eureka中的DiscoveryClient实现
@SpringBootApplication
public class ComputeServiceApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ComputeServiceApplication.class).web(true).run(args);
}
}
在浏览器中输入http://localhost:8762/hello?name=Sherry或http://yfywyangsx.hiersun.com:hello-service:8762/hello?name=Sherry
##
我们可以采用集群的方式来解决。 比如现在有三台机器:Server1、Server2和Server3.在高可用方案中,三台机器要两两注册。比如S1要向S2、S3分别进行注册,目前他无法实现注册的传递性。 这样一来,如果Server1宕机,我们还可以继续从Server2和3中获取服务。
我们来比较一下,在CAP理论中,zk更看重C和P,即一致性和分区容错性。但Eureka更在意的是A和P,A为高可用。zk中有master和follower区别,当进入选举模式时,就无法正常对外提供服务。但Eureka中,集群是对等的,地位是相同的,虽不能保证一致性,但至少可以提供注册服务。 根据不同的业务场景,各有取舍吧。