SpringCloud学习笔记(一)
1.Eureka
– springCloud Eureka 主要负责完成微服务架构中的服务治理功能。springCloud为Eureka增加了springBoot风格的自动化配置,我们只需通过简单的引入依赖和注解配置就能让springBoot构建的微服务应用轻松的与Eureka服务治理体系进行整合。
话不多说,上代码:
pom.xml依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
application.yml 配置:
spring:
application:
name: eureka
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:${server.port}/eureka/
在springboot启动类添加@EnableEurekaServer注解
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
完成这些简单的配置,就可以启动Eureka服务了。
这仅是单一服务注册中心,若想实现高可用服务注册中心,则可以将A注册中心的服务向B注册中心注册,B则反之,这样可以形成一组相互注册的服务注册中心。以实现服务注册中心的服务清单相互同步,达到高可用的效果。如下图所示:
2.SpringCloud Ribbon 负载均衡
– SpringCloud Ribbon 是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现。通过SpringCloud的封装。可以轻松的将面向服务的REST模板请求自动转换成负载均衡的服务调用。Ribbon虽然只是一个工具类框架,它不像服务注册中心、配置中心、API网关那样需要独立配置,他几乎存在于每一个SpringCloud构建的微服务和基础设施中,因为微服务之间的调用、API网关的请求转发等,实际上都是通过Ribbon来实现的。所以,对于SpringCloudRibbon的理解和使用,对学习和使用SpringCloud非常重要。
通过SpringCloudRibbon的封装,在微服务架构中使用客户端负载均衡十分简单,仅需两步:
- 服务提供者只需启动多个服务实例并注册到一个注册中心或是多个相关联的服务注册中心。
- 服务消费者直接通过被调用@LoadBalanced注解修饰过的RestTemplate来实现面向服务的接口调用。
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
3. Zuul网关
pom文件引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
yml配置文件:
spring:
application:
name: zuul
server:
port: 8080
zuul:
routes:
hello1:
path: /service1/**
serviceId: service
stripPrefix: false
hello2:
path: /service2/**
serviceId: service2
stripPrefix: false
#hystrix:
# commad:
# default:
# execution:
# isolation:
# thread:
# timeoutInMilliseconds: 10000
#
#
#ribbon:
# ConnectTimeout: 1000
# ReadTimeout: 10000
在主类上添加注解
@EnableZuulProxy
完成这些配置,即可开启Zuul的API网关服务功能。