这是我参与新手入门的第3篇文章
1.Eureka
服务注册中心,把生产者的地址注册到服务注册中心;并提供相应的地址给消费者调用。
//配置文件
spring.application.name=eureka-server
server.port=8000
eureka.instance.hostname=localhost
#fetch-registry获取注册表,不需要同步其他节点数据
eureka.client.fetch-registry=false
#register-with-eureka代表是否将自己注册到Eureka Server,默认是true
eureka.client.register-with-eureka=false
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
//在自己的模块中引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
*在应提供服务的生产者模块中
//在对应提供服务的生产者pom文件中引入client的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
//在对应提供服务的生产者配置文件中加入eureka的路径
eureka.client.service-url.defaultZone=http://localhost:8000/eureka/
2.利用Feign实现服务间的调用
在相应的业务层添加依赖
<!--feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在调用服务的启动类添加注解
@EnableFeignClients
创建接口类
@FeignClient("course-list")
public interface CourseListClient {
@GetMapping("/course")
List<Course> courseList();
}
与普通service类一样调用,@Autowired即可
3.负载均衡
客户的调用优先打到Nginx,由Nginx实现负载均衡;
Ribbon是内部模块之间的调用,实现负载均衡的,Ribbon不需要走到Nginx,避免链路加长。
RamdomRule 随机策略:即随机一个节点
RoundRobinRule 轮询策略:即轮着来,1、2、3节点顺序轮着
ResponseTimeWeightedRule 加权:即视响应时间,而分配,参考RabbitMQ的work模式
4.Hystrix断路器
在业务层加入依赖
<!--Hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在配置文件加入
feign.hystrix.enabled=true
在feign的client接口中加入
@FeignClient(value = "course-list",fallback = CourseListClientHystrix.class)
Hystrix断路器的意思就是当用户调用服务失败或长时间无服务时,跳转的一个备用方案;提升用户体验
5.网关Zuul
用户通过访问API(即网关)转发到各个服务接口;各个服务的接口地址并不会直接放到网关,地址优先注册到服务注册中心,并由服务注册中心告知网关,网关得以知道各个服务地址并调用。