1.服务治理介绍
1.1 什么是服务治理
服务治理是微服务架构中最核心最基本的模块。用于实现各个微服务的自动化注册与发现。
服务注册:在服务治理框架中,都会构建一个注册中心,每个服务单元向注册中心登记自己提供服
务的详细信息。并在注册中心形成一张服务的清单,服务注册中心需要以心跳的方式去监测清单中
的服务是否可用,如果不可用,需要在服务清单中剔除不可用的服务。
服务发现:服务调用方向服务注册中心咨询服务,并获取所有服务的实例清单,实现对具体服务实
例的访问。
通过上图会发现,除了微服务,还有一个组件是服务注册中心,它是微服务架构非常重要
的一个组件,在微服务架构里主要起到了协调者的一个作用。注册中心一般包含如下几个功能:
1. 服务发现:
服务注册:保存服务提供者和服务调用者的信息
服务订阅:服务调用者订阅服务提供者的信息,注册中心向订阅者推送提供者的信息
2. 服务配置:
配置订阅:服务提供者和服务调用者订阅微服务相关的配置
配置下发:主动将配置推送给服务提供者和服务调用者
3. 服务健康检测
检测服务提供者的健康情况,如果发现异常,执行服务剔除
2 常见的注册中心
2.1.Zookeeper
zookeeper是一个分布式服务框架,是Apache Hadoop 的一个子项目,它主要是用来解决分布式 应用中经常遇到的一些数据管理问题,如:统一命名服务、状态同步服务、集群管理、分布式应用 配置项的管理等。
2.2.Eureka
Eureka是Springcloud Netflix中的重要组件,主要作用就是做服务注册和发现。但是现在已经闭源
2.3.Consul
Consul是基于GO语言开发的开源工具,主要面向分布式,服务化的系统提供服务注册、服务发现 和配置管理的功能。Consul的功能都很实用,其中包括:服务注册/发现、健康检查、Key/Value 存储、多数据中心和分布式一致性保证等特性。Consul本身只是一个二进制的可执行文件,所以 安装和部署都非常简单,只需要从官网下载后,在执行对应的启动脚本即可。
2.4.Nacos (服务治理 配置中心)
Nacos是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。它是 Spring Cloud Alibaba 组件之一,负责服务注册发现和服务配置,可以这样认为 nacos=eureka+config。
二 nacos简介
Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速 实现动态服务发现、服务配置、服务元数据及流量管理。
从上面的介绍就可以看出,nacos的作用就是一个注册中心,用来管理注册上来的各个微服务。
三 nacos实战入门
1.搭建nacos环境
1.1 安装 nacos
下载地址: https://github.com/alibaba/nacos/releases
下载zip格式的安装包,然后进行解压缩操作
1.2 启动nacos
进入nacos 文件的bin里面 双击 startup.cmd 启动
也可以进入cmd 中输入命令启动
#切换目录
cd nacos/bin
#命令启动
startup.cmd -m standalone
1.3 访问nacos
打开浏览器输入http://localhost:8848/nacos,即可访问服务, 默认密码是nacos/nacos
2.将商品微服务注册到nacos中
修改 shop-order 模块的代码, 将其注册到nacos服务上
2.1在pom.xml中添加nacos的依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2.2在主启动类上添加nacos的开启注解
2.3 在applica.yml 中添加 nacos的配置
server:
port: 8082
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springcloud?serverTimezone=Asia/Shanghai
username: root
password: 123456
#为微服务起名
application:
name: shop-order
cloud:
nacos:
server-addr: localhost:8848
logging:
level:
com.xyf.order.mapper: debug
2.4 启动服务, 观察nacos的控制面板中是否有注册上来的商品微服务
3.将订单微服务注册到nacos
修改 shop_project 模块的代码, 将其注册到nacos服务上
3.1 在pom.xml中添加nacos的依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
</dependency>
3.2 在主启动类上添加nacos的开启注解
3.3在application.yml中添加nacos服务的地址
3.4启动服务, 观察nacos的控制面板中是否有注册上来的商品微服务
3.5 修改OrderController中的代码
package com.xyf.order.controller;
import com.xyf.entiy.Order;
import com.xyf.entiy.Product;
import com.xyf.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
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;
/**
* @program: springcloud-parent
* @description: 订单的控制层
* @author:
* @create: 2021-07-06 18:51
**/
@RestController
@Slf4j
@RequestMapping("order")
public class OrderController {
@Autowired
private OrderService orderService;
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/pro/{pid}")
public Order order(@PathVariable("pid")Long pid){
List<ServiceInstance> instances = discoveryClient.getInstances("shop-product");
ServiceInstance instance=instances.get(0);
Product product=restTemplate.getForObject(instance.getUri()+"/product/findById/"+pid,Product.class);
Order order=new Order();
order.setPid(product.getPid());
order.setPname(product.getPname());
order.setPprice(product.getPprice());
order.setUid(111);
order.setNumber(1);
order.setUsername("xyf");
orderService.save(order);
return order;
}
}
DiscoveryClient是专门负责服务注册和发现的,我们可以通过它获取到注册到注册中心的所有服
务。
6.启动服务 证调用是否成功
4 实现服务调用的负载均衡
1.什么是负载均衡
通俗的讲, 负载均衡就是将负载(工作任务,访问请求)进行分摊到多个操作单元(服务器,组件)上进行执行。
根据负载均衡发生位置的不同,一般分为服务端负载均衡和客户端负载均衡。
服务端负载均衡指的是发生在服务提供者一方,比如常见的nginx负载均衡
而客户端负载均衡指的是发生在服务请求的一方,也就是在发送请求之前已经选好了由哪个实例处理请求
我们在微服务调用关系中一般会选择客户端负载均衡,也就是在服务调用的一方来决定服务由哪个提供者执行.
2.自定义实现负载均衡
2.1 通过idea再启动一个 shop-product 微服务,设置其端口为8083
2.2 通过nacos查看微服务的启动情况
2.3修改 shop-order 的代码,实现负载均衡
package com.xyf.order.controller;
import com.xyf.entiy.Order;
import com.xyf.entiy.Product;
import com.xyf.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
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;
/**
* @program: springcloud-parent
* @description: 订单的控制层
* @author:
* @create: 2021-07-06 18:51
**/
@RestController
@Slf4j
@RequestMapping("order")
public class OrderController {
@Autowired
private OrderService orderService;
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/pro/{pid}")
public Order order(@PathVariable("pid")Long pid){
List<ServiceInstance> instances = discoveryClient.getInstances("shop-product");
int index=new Random().nextInt(instances.size());
ServiceInstance instance=instances.get(index);
Product product=restTemplate.getForObject(instance.getUri()+"/product/findById/"+pid,Product.class);
Order order=new Order();
order.setPid(product.getPid());
order.setPname(product.getPname());
order.setPprice(product.getPprice());
order.setUid(111);
order.setNumber(1);
order.setUsername("");
orderService.save(order);
return order;
}
}
2.4 测试结果
3. 基于Ribbon实现负载均衡 ---组件
1.什么是Ribbon
是 Netflix 发布的一个负载均衡器,有助于控制 HTTP 和 TCP客户端行为。在 SpringCloud 中, nacos一般配合Ribbon进行使用,Ribbon提供了客户端负载均衡的功能,Ribbon利用从nacos中读 取到的服务信息,在调用服务节点提供的服务时,会合理(策略)的进行负载。 在SpringCloud中可以将注册中心和Ribbon配合使用,Ribbon自动的从注册中心中获取服务提供者的 列表信息,并基于内置的负载均衡算法,请求服务。
是 Netflix 发布的一个负载均衡器,Ribbon自动的从注册中心中获取服务提供者的 列表信息,并基于内置的负载均衡算法,请求服务
2.Ribbon的主要作用
(1)服务调用
基于Ribbon实现服务调用, 是通过拉取到的所有服务列表组成(服务名-请求路径的)映射关系。借助 RestTemplate 最终进行调用
(2)负载均衡
当有多个服务提供者时,Ribbon可以根据负载均衡的算法自动的选择需要调用的服务地址 Ribbon是Spring Cloud的一个组件, 它可以让我们使用一个注解就能轻松的搞定负载均衡
3.操作
3.1在RestTemplate 的生成方法上添加@LoadBalanced注解
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
3.2修改服务调用的方法
package com.xyf.order.controller;
import com.xyf.entiy.Order;
import com.xyf.entiy.Product;
import com.xyf.entiy.ShopProduct;
import com.xyf.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
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;
/**
* @program: springcloud-parent
* @description: 订单的控制层
* @author:
* @create: 2021-07-06 18:51
**/
@RestController
@Slf4j
@RequestMapping("order")
public class OrderController_ribon {
@Autowired
private OrderService orderService;
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/pro/{pid}")
public Order order(@PathVariable("pid")Long pid){
ShopProduct product=restTemplate.getForObject("http://shop-product/product/findById/"+pid,ShopProduct.class);
Order order=new Order();
order.setPid((int) product.getPid());
order.setPname(product.getPname());
order.setPprice(product.getPprice());
order.setUid(111);
order.setNumber(1);
order.setUsername("xyf");
orderService.save(order);
return order;
}
}
3.3 测试结果
3.4我们可以通过修改配置来调整Ribbon的负载均衡策略
五 基于OpenFeign实现服务调用
1.什么是OpenFeign
Feign是Spring Cloud提供的一个声明式的伪Http客户端, 它使得调用远程服务就像调用本地服务一样简单, 只需要创建一个接口并添加一个注解即可。
Nacos很好的兼容了Feign, Feign负载均衡默认集成了 Ribbon, 所以在Nacos下使用Fegin默认就实现了负载均衡的效果。
2.feign使用
1.加入Feign依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.在主启动类上加入开启feign的注解
package com.xyf.order;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
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;
/**
* @program: springcloud-parent
* @description: Order主启动类
* @author:
* @create: 2021-07-06 19:00
**/
@SpringBootApplication
@MapperScan(basePackages = "com.xyf.order.mapper")
@EnableDiscoveryClient //开启nacos的注解
@EnableFeignClients //开启Feign注解
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class,args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
3. 创建feign的接口
package com.xyf.order.feign;
import com.xyf.entiy.ShopProduct;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(value = "shop-product")
@RequestMapping
public interface ProductFeign {
@GetMapping("findById/{pid}") //反射----生成接口的代理-----按照远程接口的方法实现
public ShopProduct findById(@PathVariable Long pid);
}
4.修改OrderControler的代码
package com.xyf.order.controller;
import com.xyf.entiy.Order;
import com.xyf.entiy.ShopProduct;
import com.xyf.order.feign.ProductFeign;
import com.xyf.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
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;
/**
* @program: springcloud-parent
* @description: 订单的控制层
* @author:
* @create: 2021-07-06 18:51
**/
@RestController
@Slf4j
@RequestMapping
public class OrderController_feign {
@Autowired
private OrderService orderService;
@Autowired
private ProductFeign productFeign;
@GetMapping("pro/{pid}")
public Order order(@PathVariable("pid")Long pid){
ShopProduct product= productFeign.findById(pid);
Order order=new Order();
order.setPid((int) product.getPid());
order.setPname(product.getPname());
order.setPprice(product.getPprice());
order.setUid(111);
order.setNumber(1);
order.setUsername("xyf");
orderService.save(order);
return order;
}
}
测试结果