SpringCloud基础(1)

来源:互联网 发布:程序员入门知识 编辑:程序博客网 时间:2024/06/06 20:38

参考:http://bbs.springcloud.com.cn/d/1-dd-spring-cloud。

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@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        new SpringApplicationBuilder(Application.class).web(true).run(args);    }}

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

server.port=1111eureka.client.register-with-eureka=falseeureka.client.fetch-registry=falseeureka.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的结果:

@RestControllerpublic 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@SpringBootApplicationpublic class ComputeServiceApplication {    public static void main(String[] args) {        new SpringApplicationBuilder(ComputeServiceApplication.class).web(true).run(args);    }}

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

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

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

1.3 创建服务消费者

Ribbon是一个基于HTTP和TCP客户端的负载均衡器,可以在通过客户端中配置的ribbonServiceList服务端列表去轮询访问达到负载均衡的作用。
当Ribbon和Eureka联合使用时,tibbonServerList会被DiscoveryNIWSServerList重写,扩展成从Eureka注册中心中获取服务端列表。同时它会用NIWSDiscoveryPing来取代IPing,它将职责委托给Eureka来确定服务端是否已经启动。
下面通过实例来使用Ribbon调度服务,实现客户端的负载均衡。
复制一个服务提供者,将其服务端口改为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@EnableDiscoveryClientpublic 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的值。

@RestControllerpublic 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-consumerserver.port=3333eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

当服务注册中心,服务提供者和消费者都启动之后,多次访问http://localhost:3333/add,查看服务提供者的控制台输出信息,会发现服务请求轮流被分配给两个服务提供者。
以上服务消费者使用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@EnableFeignClientspublic 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服务绑定为该接口的实现。
实现调用接口:

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

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

spring.application.name=feign-consumerserver.port=5555eureka.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。即是说,尽管只向其中一个注册中心注册了服务,但实际上所有注册中心上都拥有该服务,注册中心的节点会向整个注册中心集群传播服务提供者。因此可以得出一个结论:两两注册的方式可以实现集群中节点完全对等的效果,实现最高可用性集群,任何一台注册中心故障都不会影响服务的注册与发现