Nacos注册中心和服务消费方式
创始人
2024-02-24 02:20:11
0

目录

一,服务治理介绍

什么是服务治理?

常见的注册中心  

二,nacos简介

三,搭建nacos环境

 四,代码演示

五,基于Feign实现服务调用

什么是Feign

Feign的使用

Feign参数传递


一,服务治理介绍

什么是服务治理?

服务治理是微服务架构中最核心最基本的模块。用于实现各个微服务的自动化注册与发现

  • 服务注册:在服务治理框架中,都会构建一个注册中心,每个服务单元向注册中心登记自己提供服 务的详细信息。并在注册中心形成一张服务的清单,服务注册中心需要以心跳的方式去监测清单中 的服务是否可用,如果不可用,需要在服务清单中剔除不可用的服务。

  • 服务发现:服务调用方向服务注册中心咨询服务,并获取所有服务的实例清单,实现对具体服务实 例的访问。

 参考图

通过上面的调用图会发现,除了微服务,还有一个组件是服务注册中心,它是微服务架构非常重要 的一个组件,在微服务架构里主要起到了协调者的一个作用。注册中心一般包含如下几个功能:

  1. 服务发现:

    • 服务注册:保存服务提供者和服务调用者的信息

    • 服务订阅(发现):服务调用者订阅服务提供者的信息,注册中心向订阅者推送提供者的信息

  2. 服务配置:

    • 配置订阅:服务提供者和服务调用者订阅微服务相关的配置

    • 配置下发:主动将配置推送给服务提供者和服务调用者

  3. 服务健康检测

    • 检测服务提供者的健康情况,如果发现异常,执行服务剔除

常见的注册中心  

  • Zookeeper zookeeper是一个分布式服务框架,是Apache Hadoop 的一个子项目,它主要是用来解决分布式 应用中经常遇到的一些数据管理问题,如:统一命名服务、状态同步服务、集群管理、分布式应用 配置项的管理等。

  • Eureka Eureka是Springcloud Netflix中的重要组件,主要作用就是做服务注册和发现。但是现在已经闭 源

  • Consul Consul是基于GO语言开发的开源工具,主要面向分布式,服务化的系统提供服务注册、服务发现 和配置管理的功能。Consul的功能都很实用,其中包括:服务注册/发现、健康检查、Key/Value 存储、多数据中心和分布式一致性保证等特性。Consul本身只是一个二进制的可执行文件,所以 安装和部署都非常简单,只需要从官网下载后,在执行对应的启动脚本即可。

  • Nacos Nacos是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。它是 Spring Cloud Alibaba 组件之一,负责服务注册发现和服务配置,可以这样认为nacos=eureka+config。

二,nacos简介

Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速 实现动态服务发现、服务配置、服务元数据及流量管理。 从上面的介绍就可以看出,nacos的作用就是一个注册中心,用来管理注册上来的各个微服务。

三,搭建nacos环境

(上期我们讲了微服务的搭建,这期我们将利用上期的环境将微服务注册到nacos上去)

第一步:我们先安装nacos

下载地址: https://github.com/alibaba/nacos/releases
下载zip格式的安装包,然后进行解压缩操作

 第二步:启动nacos(找到nacos的安装路径,然后切换到nacos的bin目录下,cmd打开命令窗口 )执行命令如下:

切换目录
cd nacos/bin
命令启动
startup.cmd -m standalone

效果如图

 

还有第二种方式:直接修改startup.cmd文件:将文件中的 set MODE="cluster" 改为set MODE="standalone"

第三步:直接访问nacos

打开浏览器输入http://localhost:8848/nacos,即可访问服务, 默认密码是nacos/nacos

访问时里面啥也没有,启动完毕

 四,代码演示

将商品,用户以及订单微服务注册到nacos

第一步:找到商品模块的代码,将以下nacos依赖加到pom.xml文件中


com.alibaba.cloudspring-cloud-starter-alibaba-nacos-discovery

切记:检查父模块中是否导入了alibaba,如果没到,上面依赖会一直报错

org.springframework.cloudspring-cloud-dependencies${spring-cloud.version}pomimportcom.alibaba.cloudspring-cloud-alibaba-dependencies${spring-cloud-alibaba.version}pomimport

第二步:在主类上面添加注解@EnableDiscoveryClient

package com.dengxiyan.shoporder;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;@EnableFeignClients//开启Fegin
@EnableDiscoveryClient
@SpringBootApplication
public class ShopOrderApplication {public static void main(String[] args) {SpringApplication.run(ShopOrderApplication.class, args);}}

第三步:在application.yml文件中添加nacos服务地址

spring:cloud:nacos:discovery:server-addr: localhost:8848

第四步:启动服务, 观察nacos的控制面板中是否有注册上来的商品微服务

切换至服务管理 

 在实现将订单微服务注册到nacos上去时,需要在订单的控制层(OrderController)中,实现微服务调用

第一种方式就是将微服务注册到nacos上去

第二种方式:DiscoveryClient负载均衡实现

package com.dengxiyan.shoporder.controller;import com.dengxiyan.model.Order;
import com.dengxiyan.model.Product;
import com.dengxiyan.model.User;
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.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 dxy* @site www.javadxy.com* @company ds公司* @create  2022-11-24 16:21*/
@RestController
@RequestMapping("/order")
public class OrderController_DiscoveryClient {@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate DiscoveryClient discoveryClient;@RequestMapping("/get/{uid}/{pid}")public Order get(@PathVariable("uid") Integer uid,@PathVariable("pid") Integer pid){//我们可以通过服务名,拿到各个节点的信息List serviceInstances = discoveryClient.getInstances("shop-product");//随机产生0或者1的证书int index = new Random().nextInt(serviceInstances.size());ServiceInstance serviceInstance = serviceInstances.get(index);String url = serviceInstance.getHost() + ":" +serviceInstance.getPort();/*** 要在订单微服务调用  用户微服务  商品微服务  也意味着跨项目调用*/User user = restTemplate.getForObject("http://localhost:8070/user/get/" +uid,User.class);Product product = restTemplate.getForObject("http://"+url+"/product/get/" +pid,Product.class);Order order = new Order();order.setNumber(2);order.setOid(System.currentTimeMillis());order.setPid(pid);order.setPname(product.getPname());order.setPprice(product.getPprice() * order.getNumber());order.setUid(user.getUid());order.setUsername(user.getUsername());return order;}
}

当前的每一个服务器上都只有一个节点,为了演示效果更佳,我们在加一个节点,这边选择在订单服务器中新增一个节点,找到Run/Debug Configuration 打开编辑

 选中需要添加节点的服务器,点击复制,修改name即可

 

 访问时,访问的是同一个服务器,但经过的端口不一样

 第一次访问(使用打印方式区分)访问的是8081

 第二次访问

第三次访问 

 

 

第三种方式:Ribbon负载均衡实现

Ribbon是Spring Cloud的一个组件, 它可以让我们使用一个注解就能轻松的搞定负载均衡

第一步:在RestTemplate 的生成方法上添加@LoadBalanced注解

package com.dengxiyan.shoporder;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;@EnableDiscoveryClient
@SpringBootApplication
public class ShopOrderApplication {public static void main(String[] args) {SpringApplication.run(ShopOrderApplication.class, args);}//rebbon 负载均衡添加@LoadBalanced@Beanpublic RestTemplate getRestTemplte(){return new RestTemplate();}
}

第二步:修改服务调用的方法(当采用http://shop_product/product/get/这种方式访问第三方服务,localhost:8070不生效

package com.dengxiyan.shoporder.controller;import com.dengxiyan.model.Order;
import com.dengxiyan.model.Product;
import com.dengxiyan.model.User;
import org.springframework.beans.factory.annotation.Autowired;
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 dxy* @site www.javadxy.com* @company ds公司* @create  2022-11-24 16:21*/
@RestController
@RequestMapping("/order")
public class OrderController_Ribbon {@Autowiredprivate RestTemplate restTemplate;@RequestMapping("/get/{uid}/{pid}")public Order get(@PathVariable("uid") Integer uid,@PathVariable("pid") Integer pid){/*** * 要在订单微服务调用  用户微服务  商品微服务  也意味着跨项目调用*/User user = restTemplate.getForObject("http://localhost:8070/user/get/" +uid,User.class);Product product = restTemplate.getForObject("http://shop_product/product/get/" +pid,Product.class);Order order = new Order();order.setNumber(2);order.setOid(System.currentTimeMillis());order.setPid(pid);order.setPname(product.getPname());order.setPprice(product.getPprice() * order.getNumber());order.setUid(user.getUid());order.setUsername(user.getUsername());return order;}
}

补充:

Ribbon支持的负载均衡策略 Ribbon内置了多种负载均衡策略,内部负载均衡的顶级接口为

具体如下图

 

以上三种方式都不推荐使用,原因为了更好的了解演变效果~~~~~接下来就讲讲Feign的基本使用

相较于以上三种,Feign更为推荐

五,基于Feign实现服务调用

什么是Feign

Feign是Spring Cloud提供的一个声明式的伪Http客户端, 它使得调用远程服务就像调用本地服务 一样简单, 只需要创建一个接口并添加一个注解即可。 Nacos很好的兼容了Feign, Feign默认集成了 Ribbon, 所以在Nacos下使用Fegin默认就实现了负 载均衡的效果。

Feign的使用

第一步:加入pom依赖(加在基础模块里面)


org.springframework.cloudspring-cloud-starter-openfeign

第二步: 在主类上添加Fegin的注解

package com.dengxiyan.shoporder;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;@EnableFeignClients//开启Fegin
@EnableDiscoveryClient
@SpringBootApplication
public class ShopOrderApplication {public static void main(String[] args) {SpringApplication.run(ShopOrderApplication.class, args);}//rebbon 负载均衡添加@LoadBalanced@Beanpublic RestTemplate getRestTemplte(){return new RestTemplate();}
}

第三步:创建一个service, 并使用Fegin实现微服务调用

package com.dengxiyan.shoporder.service;import com.dengxiyan.model.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;@FeignClient("shop-product")//声明调用的提供者的name
public interface ProductService {//指定调用提供者的哪个方法//@FeignClient+@GetMapping 就是一个完整的请求路径//http://serviceproduct/product/{pid}@GetMapping(value = "/product/get/{pid}")Product findByPid(@PathVariable("pid") Integer pid);}

第四步: 修改controller代码,并启动验证

package com.dengxiyan.shoporder.controller;import com.dengxiyan.model.Order;
import com.dengxiyan.model.Product;
import com.dengxiyan.model.User;
import com.dengxiyan.shoporder.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
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 dxy* @site www.javadxy.com* @company ds公司* @create  2022-11-24 16:21*/
@RestController
@RequestMapping("/order")
public class OrderController_Feign {@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate ProductService productService;@RequestMapping("/get/{uid}/{pid}")public Order get(@PathVariable("uid") Integer uid,@PathVariable("pid") Integer pid){User user = restTemplate.getForObject("http://spring-user/user/get/" +uid,User.class);Product product = productService.findByPid(pid);Order order = new Order();order.setNumber(2);order.setOid(System.currentTimeMillis());order.setPid(pid);order.setPname(product.getPname());order.setPprice(product.getPprice() * order.getNumber());order.setUid(user.getUid());order.setUsername(user.getUsername());return order;}
}

Feign参数传递

在商品微服务中添加服务的提供方

代码如下

package com.dengxiyan.shopproduct.controller;import com.dengxiyan.model.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;@Slf4j
@RestController
@RequestMapping("/feign/server")
public class FeignServerController {@RequestMapping("/findByParameter")public String findByParameter(String name,Double price){log.info("服务提供者日志:{}",name);return "hello:"+name;}@RequestMapping("/findByParameter2")public String findByParameter2(@RequestParam("name") String name,@RequestParam("price") Double price){log.info("服务提供者日志:{},{}",name,price);return "hello:"+name+price;}@RequestMapping("/findByPathVariable/{name}")public String findByPathVariable(@PathVariable("name") String name){log.info("服务提供者日志:{}",name);return "hello:"+name;}@RequestMapping("/findByRequestBody")public Product findByRequestBody(@RequestBody Product product){log.info("服务提供者日志:{}",product.getPname());return product;}
}

同时在调用方接口处也加上服务提供方的方法

代码如下

package com.dengxiyan.shoporder.service;import com.dengxiyan.model.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;@FeignClient("shop-product")//声明调用的提供者的name
public interface ProductService {//指定调用提供者的哪个方法//@FeignClient+@GetMapping 就是一个完整的请求路径//http://serviceproduct/product/{pid}@GetMapping(value = "/product/get/{pid}")Product findByPid(@PathVariable("pid") Integer pid);@RequestMapping("/feign/server/findByParameter")public String findByParameter(@RequestParam("name") String name,@RequestParam("price") Double price);@RequestMapping("/feign/server/findByParameter2")public String findByParameter2(@RequestParam("name") String name,@RequestParam("price") Double price);@RequestMapping("/feign/server/findByPathVariable/{name}")String findByPathVariable(@PathVariable("name") String name);@RequestMapping("/feign/server/findByRequestBody")Product findByRequestBody(@RequestBody Product product);}

利用测试工具测试代码效果

相关内容

热门资讯

【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
ChatGPT 怎么用最新详细... ChatGPT 以其强大的信息整合和对话能力惊艳了全球,在自然语言处理上面表现出了惊人...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...