• 第十八章 Nacos注册中心详解-入门案例


    目录

    一、Spring Cloud Alibaba 基础环境搭建

    二、Nacos客户端服务环境搭建

    2.1 创建基于Nacos的服务消费者和提供者

    2.2 引入 Nacos Client 依赖

    2.3 编写配置,服务注册到 Nacos 中心

    2.4 创建主启动类

    2.5 启动测试

    三、服务间通信

    1. 服务将通信方式

    2. 使用Rest通信方式实现服务通信

    3. 使用OpenFegin接口实现负载均衡及通信 

    4. 启动测试


    一、Spring Cloud Alibaba 基础环境搭建

          见 第十六章 Spring Cloud Alibaba 基础环境搭建  对应版本如下:

    springbootSpring CloudSpring Cloud AlibabaNacosSentinelRocketMQSeataDubbo
     2.6.11 2021.0.42021.0.4.02.0.41.8.54.9.41.5.2~

    二、Nacos客户端服务环境搭建

            Nacos客户端服务创建的步骤是:创建独立的springboot应用、引入依赖、编写配置、创建主启动类、创建业务类、启动测试。

    2.1 创建基于Nacos的服务消费者和提供者

    •  新建两个服务提供者和一个服务消费者模块,分别为:    

            cloudalibaba-product-server9001

            cloudalibaba-product-server9002

            cloudalibaba-order-server9000

    2.2 引入 Nacos Client 依赖

    •  服务提供者和服务消费者引入Nacos客户端依赖

            引入服务提供者 cloudalibaba-product-server9001 与  cloudalibaba-product-server9002 及服务消费者 cloudalibaba-order-server9000 的 Nacos client 依赖。三个的pom文件都相同。唯一不同就是 groupId 与 artifactId。我们以 消费者为案例。

    服务消费者引入 Nacos Client 依赖
    
    
        
            springcloudalibaba
            com.hwadee.springcloud2022
            0.0.1-SNAPSHOT
        
        4.0.0
       
        com.hwadee.springcloud
        cloudalibaba-order-server9000
    
        
            
            
                com.alibaba.cloud
                spring-cloud-starter-alibaba-nacos-discovery
            
    
            
            
                org.springframework.boot
                spring-boot-starter-web
            
            
            
                com.hwadee.springcloud
                springcloud-api
                0.0.1-SNAPSHOT
            
        
    
    

    不同部分

        com.hwadee.springcloud
        cloudalibaba-order-server9000

        com.hwadee.springcloud
        cloudalibaba-product-server9001

        com.hwadee.springcloud
        cloudalibaba-product-server9002

    2.3 编写配置,服务注册到 Nacos 中心

         编写服务提供者和服务消费者的配置,在配置文件中需要配置注册服务的名称和注册中心的地址。如:

    • 注册服务的名称 spring.application.name=ORDER-SERVICE-CUSTOMER
    • 注册服务的名称 spring.cloud.nacos.discovery.service=${spring.application.name}
    • 注册的地址 spring.cloud.nacos.server-addr=localhost:8848
    • 注册的地址 spring.cloud.nacos.discovery.server-addr=${spring.cloud.nacos.server-addr}

           配置中 spring.cloud.nacos.server-addr 是Nacos server总地址,客户端的注册地址是spring.cloud.nacos.discovery.server-addr,二者区别是spring.cloud.nacos.discovery.server-addr默认值是spring.cloud.nacos.server-addr是Nacos server总地址,因此在配置文件中可以只配置总地址也可以 即 spring.cloud.nacos.server-addr。同理,spring.cloud.nacos.discovery.service默认值也是spring.application.name,因此也可以只配置spring.application.name 。

            配置文件分别如下:

    • 服务消费者 order-server 配置文件
    server:
      port: 9000
    
    spring:
      application:
        name: ORDER-SERVICE-CUSTOMER
      cloud:
        #配置 nacos server 注册中心总的地址
        nacos:
          server-addr: localhost:8848 # 配置nacos server 注册中心地址
    • 服务提供者 product-server 两个配置文件分别如下:
    server:
      port: 9001
    
    spring:
      application:
        name: PRODUCT-SERVICE-PROVIDER
      cloud:
        #配置 nacos server 注册中心总的地址
        nacos:
          server-addr: localhost:8848 # 配置nacos server 注册中心地址
    

    server:
      port: 9002
    
    spring:
      application:
        name: PRODUCT-SERVICE-PROVIDER
      cloud:
        #配置 nacos server 注册中心总的地址
        nacos:
          server-addr: localhost:8848 # 配置nacos server 注册中心地址
    
    

    2.4 创建主启动类

           创建服务提供者和服务消费者的主启动类,分别如下:

    • OrderServerApplication
    1. @SpringBootApplication
    2. public class OrderServerApplication {
    3. public static void main(String[] args) {
    4. SpringApplication.run(OrderServerApplication.class, args);
    5. }
    6. }
    • ProductServerApplication
    1. @SpringBootApplication
    2. public class ProductServerApplication {
    3. public static void main(String[] args) {
    4. SpringApplication.run(ProductServerApplication.class, args);
    5. }
    6. }

    2.5 启动测试

    三、服务间通信

    1. 服务将通信方式

    •   1、Http Rest(推荐)
    •   2、RPC(不推荐)

    2. 使用Rest通信方式实现服务通信

    •   1、RestTemplate(不推荐)
    •   2、RestTemplate + Ribbon(不推荐)
    •   3、OpenFeign(推荐)

    3. 使用OpenFegin接口实现负载均衡及通信 

    • 引入依赖

           消费者 order-service9000 引入 OpenFegin 依赖 ,修改pom文件,如下:

     
           
           
               org.springframework.cloud
               spring-cloud-starter-openfeign
           

    注意:此处因为由于SpringCloud Feign在Hoxton.M2 RELEASED版本之后不再使用Ribbon,而是使用spring-cloud-loadbalancer,所以要引入spring-cloud-loadbalancer,不引入会报错。

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <parent>
    5. <artifactId>springcloudalibabaartifactId>
    6. <groupId>com.hwadee.springcloud2022groupId>
    7. <version>0.0.1-SNAPSHOTversion>
    8. parent>
    9. <modelVersion>4.0.0modelVersion>
    10. <groupId>com.hwadee.springcloudgroupId>
    11. <artifactId>cloudalibaba-order-server9000artifactId>
    12. <dependencies>
    13. <dependency>
    14. <groupId>org.springframework.cloudgroupId>
    15. <artifactId>spring-cloud-starter-openfeignartifactId>
    16. dependency>
    17. <dependency>
    18. <groupId>org.springframework.cloudgroupId>
    19. <artifactId>spring-cloud-loadbalancerartifactId>
    20. dependency>
    21. <dependency>
    22. <groupId>com.alibaba.cloudgroupId>
    23. <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
    24. dependency>
    25. <dependency>
    26. <groupId>org.springframework.bootgroupId>
    27. <artifactId>spring-boot-starter-webartifactId>
    28. dependency>
    29. <dependency>
    30. <groupId>com.hwadee.springcloudgroupId>
    31. <artifactId>springcloud-apiartifactId>
    32. <version>0.0.1-SNAPSHOTversion>
    33. dependency>
    34. dependencies>
    35. project>
    • 编写消费者 OpenFegin 接口

            编写消费者 order-service9000 的 OpenFegin 接口,在订单服务中的service目录中创建 调用远端服务的接口 IOrderFeignService  ,在接口上使用注解 @FeignClient("PRODUCT-SERVICE-PROVIDER"),表示 controller 调用接口方法时候,使用负载均衡机制,进行寻找服务名为 "PRODUCT-SERVICE-PROVIDER" 的远端服务,接口中的方法和controller中的方法写法类似。代码如下:

    1. import com.hwadee.springcloud.entity.Product;
    2. import org.springframework.cloud.openfeign.FeignClient;
    3. import org.springframework.stereotype.Component;
    4. import org.springframework.web.bind.annotation.PathVariable;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. @Component // 让 spring 可以识别,不加也行,但是在注入的时候 IDEA 会报错,不会影响运行,但有条红线让自己不舒服
    7. @FeignClient("PRODUCT-SERVICE-PROVIDER")
    8. public interface IOrderFeignService {
    9. @RequestMapping(value = "/product/buy/{id}")
    10. Product findOrderById(@PathVariable Long id);
    11. }
    • 创建controller

           编写消费者 order-service9000 和 product-server9001 及 product-server9002的 Controller,分别如下:

    • OrderController
    • 在订单服务中创建 OrderController ,在 OrderController 中注入 IOrderFeignService  接口,通过 IOrderFeignService 接口方法 调用远端服务,代码如下:
    1. import com.hwadee.springcloud.entity.Product;
    2. import com.hwadee.springcloud.service.IOrderFeignService;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.web.bind.annotation.PathVariable;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RestController;
    7. @RestController
    8. @RequestMapping("/order")
    9. public class OrderController {
    10. @Autowired
    11. IOrderFeignService orderFeignService;
    12. @RequestMapping("/buy/{id}")
    13. public Product buy(@PathVariable Long id) {
    14. Product product = orderFeignService.findOrderById(id);
    15. return product;
    16. }
    17. }
    • ProductController
    1. import com.hwadee.springcloud.entity.Product;
    2. import org.springframework.beans.factory.annotation.Value;
    3. import org.springframework.web.bind.annotation.PathVariable;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.RestController;
    6. import java.math.BigDecimal;
    7. @RestController
    8. @RequestMapping("/product")
    9. public class ProductController {
    10. //方便后面讲负载均衡,查看ip,此处获取配置中的端口号和ip
    11. @Value("${server.port}")
    12. private String port;
    13. @Value("${spring.cloud.client.ip-address}")
    14. private String ip;
    15. @RequestMapping("/buy/{id}")
    16. public Product findById(@PathVariable Long id) {
    17. Product product = new Product();
    18. product.setId(id);
    19. // 后面需要测试负载均衡,所以返回 ip 地址及端口号
    20. product.setName("当前访问服务地址:" + ip + ":" + port+" "+"查询商品订单,订单号:"+id);
    21. product.setPrice(new BigDecimal(10000.0));
    22. System.out.println(product);
    23. return product;
    24. }
    25. }
    • 编写消费者启动类

           编写消费者 order-service9000 的启动类,并增加注解 @EnableFeignClients 来启动 openFeign。代码如下:

    1. import org.springframework.boot.SpringApplication;
    2. import org.springframework.boot.autoconfigure.SpringBootApplication;
    3. import org.springframework.cloud.openfeign.EnableFeignClients;
    4. @SpringBootApplication
    5. @EnableFeignClients // 启动 feign
    6. public class OrderServerApplication {
    7. public static void main(String[] args) {
    8. SpringApplication.run(OrderServerApplication.class, args);
    9. }
    10. }

    4. 启动测试

    • 启动PRODUCTER-SERVICE
    • 启动ORDER-SERVICE
    • 浏览器查看  http://localhost:9001/product/buy/1 、  http://localhost:9002/product/buy/1 、  http://localhost:9000/order/buy/1 

    第十七章:Nacos注册中心详解-入门介绍

    第十九章:Nacos统一配置中心详解

  • 相关阅读:
    【附源码】计算机毕业设计JAVA家庭理财管理系统
    Redis的BitMap实现分布式布隆过滤器
    通过京东商品ID获取京东优惠券信息,京东优惠券信息接口,京东优惠券API接口,接口说明接入方案
    PromptPort:为大模型定制的创意AI提示词工具库
    Curator实现Zookeeper分布式锁
    MySQL | 查询接口性能调优、编码方式不一致导致索引失效
    【MindSpore】【训练】图模式训练过程中出现问题
    Unity减少发布打包文件的体积(二)——设置WebGL发布时每张图片的压缩方式
    使用Springboot做测试的步骤详解
    day33-线程基础03
  • 原文地址:https://blog.csdn.net/qq_41946216/article/details/127568411