目录
1 服务治理介绍
1.1 什么是服务治理
服务治理是微服务架构中最核心最基本的模块。用于实现各个微服务的自动化注册与发现。
服务注册:在服务治理框架中,都会构建一个注册中心,每个服务单元向注册中心登记自己提供服
务的详细信息。并在注册中心形成一张服务的清单,服务注册中心需要以心跳30s 90s的方式去监测清单中 的服务是否可用,如果不可用,需要在服务清单中剔除不可用的服务。
服务发现:服务调用方向服务注册中心咨询服务,并获取所有服务的实例清单,实现对具体服务实
例的访问。
通过上面的调用图会发现,除了微服务,还有一个组件是服务注册中心,它是微服务架构非常重要
的一个组件,在微服务架构里主要起到了协调者的一个作用。注册中心一般包含如下几个功能:
1. 服务发现:
服务注册:保存服务提供者和服务调用者的信息
服务订阅:服务调用者订阅服务提供者的信息,注册中心向订阅者推送提供者的信息
2. 服务配置:
配置订阅:服务提供者和服务调用者订阅微服务相关的配置
配置下发:主动将配置推送给服务提供者和服务调用者
3. 服务健康检测
检测服务提供者的健康情况,如果发现异常,执行服务剔除
1.2 常见的注册中心
1.2.1 Zookeeper
zookeeper是一个分布式服务框架,是Apache Hadoop 的一个子项目,它主要是用来解决分布式
应用中经常遇到的一些数据管理问题,如:统一命名服务、状态同步服务、集群管理、分布式应用
配置项的管理等。
1.2.2 Eureka
Eureka是Springcloud Netflix中的重要组件,主要作用就是做服务注册和发现。但是现在已经闭源 ,停更不停用。
1.2.3 Consul
Consul是基于GO语言开发的开源工具,主要面向分布式,服务化的系统提供服务注册、服务发现
和配置管理的功能。Consul的功能都很实用,其中包括:服务注册/发现、健康检查、Key/Value
存储、多数据中心和分布式一致性保证等特性。Consul本身只是一个二进制的可执行文件,所以
安装和部署都非常简单,只需要从官网下载后,在执行对应的启动脚本即可。
1.2.4 Nacos (服务治理 配置中心)
Nacos是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。它是 Spring
Cloud Alibaba 组件之一,负责服务注册发现和服务配置,可以这样认为nacos=eureka+config。
2 nacos简介
Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速
实现动态服务发现、服务配置、服务元数据及流量管理。
从上面的介绍就可以看出,nacos的作用就是一个注册中心,用来管理注册上来的各个微服务。
3 nacos实战入门
接下来,我们就在现有的环境中加入nacos,并将我们的两个微服务注册上
3.1 搭建nacos环境
第1步: 安装nacos
下载地址: https://github.com/alibaba/nacos/releases
下载zip格式的安装包,然后进行解压缩操作
第2步: 启动nacos
#切换目录
cd nacos/bin
#命令启动
startup.cmd -m standalone
第3步: 访问nacos
打开浏览器输入http://localhost:8848/nacos,即可访问服务, 默认密码是nacos/nacos
3.2 将商品微服务注册到nacos
接下来开始修改 shop-product 模块的代码, 将其注册到nacos服务上
1 在pom.xml中添加nacos的依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2 在application.yml添加nacos的配置
spring.cloud.nacos.discovery.server-addr=localhost:8848 spring.application.name=eureka-product
启动服务, 观察nacos的控制面板中是否有注册上来的商品微服务
3.3 将订单微服务注册到nacos
接下来开始修改 shop_order 模块的代码, 将其注册到nacos服务上
1 在pom.xml中添加nacos的依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2 在application.yml中添加nacos服务的地址
#配置nacos注册中心的地址
spring.cloud.nacos.discovery.server-addr=localhost:8848
#是否把nacos服务端注册到注册中心
spring.cloud.nacos.discovery.register-enabled=false
#起名
spring.application.name=nacos-order
3 启动服务, 观察nacos的控制面板中是否有注册上来的商品微服务
4 修改OrderController中的代码
package com.dyt.order.controller;
import com.dyt.entity.Order;
import com.dyt.entity.Product;
import com.dyt.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Random;
/**
* @author dyt
*/
@RestController
@RequestMapping("/order")
public class OrderController1 {
@Autowired
private OrderService orderService;
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/buy/{pid}/{num}")
public String buy(@PathVariable Integer pid,@PathVariable Integer num){
Order order = new Order();
order.setNumber(num);
order.setUid(5);
order.setUsername("赵六");
List<ServiceInstance> serviceInstances = discoveryClient.getInstances("product");
ServiceInstance instance = serviceInstances.get(new Random().nextInt(serviceInstances.size()));
String path = instance.getUri().toString();
Product product = restTemplate.getForObject(path+"/product/getById/" + pid, Product.class);
order.setPid(product.getPid());
order.setPname(product.getPname());
order.setPprice(product.getPprice());
orderService.saveOrder(order);
return "下单成功";
}
}
DiscoveryClient是专门负责服务注册和发现的,我们可以通过它获取到注册到注册中心的所有服
务。
5 启动服务, 观察nacos的控制面板中是否有注册上来的订单微服务,然后通过访问消费者服务验证调用是否成功
4 实现服务调用的负载均衡
4.1 什么是负载均衡 nginx
通俗的讲, 负载均衡就是将负载(工作任务,访问请求)进行分摊到多个操作单元(服务器,组件)上进行执行。
根据负载均衡发生位置的不同,一般分为服务端负载均衡和客户端负载均衡。
服务端负载均衡指的是发生在服务提供者一方,比如常见的nginx负载均衡
而客户端负载均衡指的是发生在服务请求的一方,也就是在发送请求之前已经选好了由哪个实例处理请求
我们在微服务调用关系中一般会选择客户端负载均衡,也就是在服务调用的一方来决定服务由哪个提供者执行.
4.2 自定义实现负载均衡
1 通过idea再启动一个 shop-product 微服务,设置其端口为8082
2 通过nacos查看微服务的启动情况
3 修改 order 的代码,实现负载均衡
package com.dyt.order.controller;
import com.dyt.entity.Order;
import com.dyt.entity.Product;
import com.dyt.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Random;
/**
* @author dyt
*/
@RestController
@RequestMapping("/order")
public class OrderController1 {
@Autowired
private OrderService orderService;
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/buy/{pid}/{num}")
public String buy(@PathVariable Integer pid,@PathVariable Integer num){
Order order = new Order();
order.setNumber(num);
order.setUid(5);
order.setUsername("赵六");
List<ServiceInstance> serviceInstances = discoveryClient.getInstances("product");
ServiceInstance instance = serviceInstances.get(new Random().nextInt(serviceInstances.size()));
String path = instance.getUri().toString();
Product product = restTemplate.getForObject(path+"/product/getById/" + pid, Product.class);
order.setPid(product.getPid());
order.setPname(product.getPname());
order.setPprice(product.getPprice());
orderService.saveOrder(order);
return "下单成功";
}
}
启动两个服务提供者和一个服务消费者,多访问几次消费者测试效果
4.3 基于Ribbon实现负载均衡 ---组件
4.3.1什么是Ribbon
是 Netflix 发布的一个负载均衡器,有助于控制 HTTP 和 TCP客户端行为。在 SpringCloud 中, nacos一般配合Ribbon进行使用,Ribbon提供了客户端负载均衡的功能,Ribbon利用从nacos中读 取到的服务信息,在调用服务节点提供的服务时,会合理(策略)的进行负载。 在SpringCloud中可以将注册中心和Ribbon配合使用,Ribbon自动的从注册中心中获取服务提供者的 列表信息,并基于内置的负载均衡算法,请求服务。
是 Netflix 发布的一个负载均衡器,Ribbon自动的从注册中心中获取服务提供者的 列表信息,并基于内置的负载均衡算法,请求服务。
4.3.2 Ribbon的主要作用
(1)服务调用
基于Ribbon实现服务调用, 是通过拉取到的所有服务列表组成(服务名-请求路径的)映射关系。借助 RestTemplate 最终进行调用
(2)负载均衡
当有多个服务提供者时,Ribbon可以根据负载均衡的算法自动的选择需要调用的服务地址
Ribbon是Spring Cloud的一个组件, 它可以让我们使用一个注解就能轻松的搞定负载均衡
第1步:在RestTemplate 的生成方法上添加@LoadBalanced注解
package com.dyt.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* @author dyt
*/
@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
public static void main(String[] args){
SpringApplication.run(OrderApplication.class,args);
}
@Bean
@LoadBalanced //轮询策略
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
修改服务调用的方法
package com.dyt.order.controller;
import com.dyt.entity.Order;
import com.dyt.entity.Product;
import com.dyt.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author dyt
*/
@RestController
@RequestMapping("/order")
public class OrderController2 {
@Autowired
private OrderService orderService;
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/buy/{pid}/{num}")
public String buy(@PathVariable Integer pid,@PathVariable Integer num){
Order order = new Order();
order.setNumber(num);
order.setUid(5);
order.setUsername("赵六");
Product product = restTemplate.getForObject("http://product/product/getById/" + pid, Product.class);
order.setPid(product.getPid());
order.setPname(product.getPname());
order.setPprice(product.getPprice());
orderService.saveOrder(order);
return "下单成功";
}
}
Ribbon支持的负载均衡策略
Ribbon内置了多种负载均衡策略,内部负载均衡的顶级接口为
com.netflix.loadbalancer.IRule , 具体的负载策略如下图所示:
我们可以通过修改配置来调整Ribbon的负载均衡策略,具体代码如下
product.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule
5 基于OpenFeign实现服务调用
5.1 什么是OpenFeign
OpenFeign是Spring Cloud提供的一个声明式的伪Http客户端, 它使得调用远程服务就像调用本地服务一样简单, 只需要创建一个接口并添加一个注解即可。
Nacos很好的兼容了Feign, Feign负载均衡默认集成了 Ribbon, 所以在Nacos下使用Fegin默认就实现了负载均衡的效果。
5.2 Feign的使用
1 加入Fegin的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2 在主启动类上加入开启feign的注解
package com.dyt.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* @author dyt
*/
@SpringBootApplication
@EnableFeignClients //开启feigin注解
public class OrderApplication {
public static void main(String[] args){
SpringApplication.run(OrderApplication.class,args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
3 创建feign的接口
package com.dyt.order.feigin;
import com.dyt.entity.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "eureka-product")
public interface ProductFeigin {
@GetMapping("product/getById/{pid}")
public Product getById (@PathVariable Integer pid);
}
4 修改OrderController的代码
package com.dyt.order.controller;
import com.dyt.entity.Order;
import com.dyt.entity.Product;
import com.dyt.entity.util.CommonResult;
import com.dyt.order.feigin.ProductFeigin;
import com.dyt.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author dyt
*/
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
@Autowired
private ProductFeigin productFeigin;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/buy/{pid}/{num}")
public Order buy(@PathVariable Integer pid,@PathVariable Integer num){
Order order = new Order();
order.setNumber(num);
order.setUid(5);
order.setUsername("赵六");
Product product = productFeigin.getById(pid);
order.setPid(product.getPid());
order.setPname(product.getPname());
order.setPprice(product.getPprice());
orderService.saveOrder(order);
return order;
}
}
5 重启order微服务,查看效果
6 使用eureka作为注册中心
6.1 什么是eureka
Eureka是Netflix开发的服务发现框架,SpringCloud将它集成在自己的子项目spring-cloud-netflix中,实现SpringCloud的服务发现功能。
- 创建一个eureka服务端
2 在eureka服务端引入相关的依赖
<?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">
<parent>
<artifactId>qy151-dyt-parent</artifactId>
<groupId>com.dyt</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>qy151-dyt-Eureak</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
</project>
3 添加application.properties文件
server.port=7001
spring.application.name=eureka-server
#实例的主机名
eureka.instance.hostname=localhost
#是否把eureka服务端注册到注册中心
eureka.client.register-with-eureka=false
#该服务是否从注册中心拉取服务
eureka.client.fetch-registry=false
#提供给微服务的地址
eureka.client.service-url.defaultZone=http://localhost:7001/eureka
4 主启动类
package Com.dyt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* @author dyt
*/
@SpringBootApplication
@EnableEurekaServer //开启注解
public class EurekaServerApp {
public static void main (String[] args){
SpringApplication.run(EurekaServerApp.class,args);
}
}
5 客户端
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
6 配置文件
spring.application.name=eureka-product eureka.client.service-url.defaultZone=http://localhost:7001/eureka