微服务系列--nacos注册中心与服务发现

2023-05-16

1、前言

终究还是到了更新关于微服务相关博客的时候了,经过挺长一段时间微服务的自主学习,现在不敢说自己熟悉微服务,但我也能略知一二。微服务嘛,其实入门之后便会发现,其实关于微服务相关的代码量其实少之又少,如果用的是SpringCloud Alibaba这一套,那代码量就更少了,微服务比较难的地方其实是在配置上面,只要配置好了,其实后面也就不关微服务的事了。好了,闲话少话,我这里并没有从SpringCloud的五大组件开始写起,而是选择从SpringCloud Alibaba开始写起,后面如果有时间,则再更新SpringCloud五大组件的内容。

2、什么是nacos

naocs其实是用java写的一个服务,相比feign,可以说是零代码,因为feign的话,一般来说都会单独使用一个工程来当注册中心,而所谓的注册中心呢,其实就是把消费者和提供者管理起来的一个容器。至于怎么启动nacos,那真的无脑启动,只需要下载后nacos后,双击启动脚本就OK了,当初我刚接触到这玩意的时候,觉得feign完全没有使用的必要了,而且比feign更加强大。

3、下载并启动nacos

下载官网:

Releases · alibaba/nacos · GitHub(直链前往)

https://github.com/alibaba/nacos/releases(网址前往)

如果下载慢,可以从我上传的资源进行下载:

nacos1.2.1.zip-Java文档类资源-CSDN下载

我这里使用的是1.2.1的版本,相对来说也比较久了,现在出到2.0以上的版本了,之所以我用这个版本呢,是因为我在刚入门的时候踩了很多坑,好多时候是因为问题出在版本不兼容上了,这是后期我整合ribbon、sentinel、gateway比较适合的一个版本。

 下载之后进行解压,在bin目录下双击startup.cmd,看到此界面便是已成功

打开浏览器,输入localhost:8848/nacos,打开nacos的可视化管理界面,这里有个小bug,有时候用localhost打开之后,会发现是一个空白页面,无法正常显示页面,那可以换成本地ip的方式进行打开,默认用户名和密码都是 nacos

 4、创建微服务父工程

创建好SpringBoot工程后,导入所需依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <packaging>pom</packaging>
    <groupId>com.chen</groupId>
    <artifactId>SpringCloudAliBaBa_Learn</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringCloudAliBaBa_Learn</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.1.RELEASE</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
            </plugin>
        </plugins>
    </build>

</project>

5、创建服务提供者模块

在创建好的SpringBoot工程下,新建一个module,名为provider,导入依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.chen</groupId>
        <artifactId>SpringCloudAliBaBa_Learn</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>com.chen</groupId>
    <artifactId>provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>provider</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
            </plugin>
        </plugins>
    </build>

</project>

yml配置,nacos的默认地址就是 localhost:8848,这是我在研究nacos源码的时候发现的,所以说如果你是在本地,那这个配置写不写都无所谓,只要你导入了依赖,启动了nacos,那就会自动将你这个服务注册到nacos里去。

spring:
  cloud:
    nacos:
      discovery:
        # 配置nacos服务地址,如果不配置,默认是localhost:8848
        server-addr: localhost:8848
  application:
    name: provider

server:
  port: 8081

接下来写一个controller进行测试

package com.chen.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/provider")
public class ProviderController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String port;

    @GetMapping("/instances")
    public List<ServiceInstance> instances() {
        List<ServiceInstance> provider = discoveryClient.getInstances("provider");
        return provider;
    }

    @GetMapping("/index")
    public String index(){
        return "ok--"+port;
    }
}

第一个 instances接口,获得provider这个实例名下的所有服务,

第二个index接口,方便我后面新加一个consumer服务进行调用。

将这个服务进行运行,打开nacos,查看服务列表,可以看到这个服务已经注册进来了

现在,我们修改这个服务的端口号,改为8082,再次运行,可以看到现在实例数已经变为2了

接着我们调第一个接口,localhost:8081/provider/instances

或者是localhost:8082/provider/instances

 6、创建服务消费者模块

同样新建module,引入依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.chen</groupId>
        <artifactId>SpringCloudAliBaBa_Learn</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>com.chen</groupId>
    <artifactId>consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>consumer</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
            </plugin>
        </plugins>
    </build>

</project>

yml配置

spring:
  cloud:
    nacos:
      discovery:
        # 配置nacos服务地址,如果不配置,默认是localhost:8848
        server-addr: localhost:8848
  application:
    name: consumer

server:
  port: 8080

我这里使用RestTemplate进行服务调用

package com.chen.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ConsumerConfig {

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

新建消费者controller,用来调第5步启动成功的那两个服务,这里我用随机数,先获得实例数,再根据实例数的大小随机调取服务

package com.chen.controller;

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/index")
    public String index(){
        List<ServiceInstance> provider = discoveryClient.getInstances("provider");
        int index = ThreadLocalRandom.current().nextInt(provider.size());
        String url = provider.get(index).getUri()+"/provider/index";
        return this.restTemplate.getForObject(url, String.class);
    }

}

启动消费者,发现在nacos中也成功注册进来了

现在调消费者的接口,localhost:8080/consumer/index

可以看到结果要么调的是 8081,要么是8082

nacos注册中心和服务发现搭建成功,后面持续整合微服务的其他组件~~~ 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

微服务系列--nacos注册中心与服务发现 的相关文章

随机推荐

  • 【YOLOv5】记录YOLOv5的学习过程

    以下记录的是Ubuntu20 04版本 xff0c 其他Ubuntu版本也相差不大 一 安装pytorch GPU版本 显卡驱动 CUDA cuDNN 下载pytorch GPU版本 xff1a 最新版本链接 xff1a Start Loc
  • 【Kinect】Ubuntu20.04 安装Azure Kinect Sensor

    本文主要记录Ubuntu20 04 安装Azure Kinect Sensor SDK Azure Kinect 人体跟踪 SDK官网 xff1a https learn microsoft com zh cn azure Kinect d
  • 【ORB_SLAM】Ubuntu20.04 配置ORB_SLAM3

    本文主要记录基于Ubuntu20 04环境下 xff0c 对普通的ORB SLAM3和稠密版本的ORB SLAM3进行环境的配置 一 配置ORB SLAM3 lt 普通版本 gt 1 安装ROS开发环境 这里采用鱼香ros的一键安装 xff
  • 【工具】记录安装Zsh

    本文主要记录下安装Zsh的过程 xff0c 方便后续换设备安装 xff01 与大家共同学习 xff01 xff08 Ubuntu 20 04 xff09 安装zsh sudo apt install zsh 2 下载oh my zsh 并安
  • 【Ubuntu】记录Ubuntu缺少启动项问题

    今天突然发现自己装的Ubuntu没有启动项 xff0c 也就是没有那个EFI分区 xff0c 人都麻了 xff01 原因是先把装Ubuntu的固态拿了出来 xff0c 再装的win11 xff0c 结果win11可以用了 xff0c Ubu
  • 【SLAM学习】基于Pangolin绘制运动轨迹

    Pangolin库 是一个轻量级的跨平台视图控制库 xff0c 主要用于可视化 交互和调试三维数据 该库提供了一系列图形界面工具 xff0c 包括窗口 OpenGL渲染器 3D相机 图像显示等 xff0c 可以方便地进行三维数据可视化和交互
  • Groovy学习-IO/文件操作

    读取文件 读取文本文件并打印每一行文本 new File 39 39 39 a txt 39 eachLine line gt println line eachLine方法是Groovy为File类自动添加的方法 xff0c 同时提供多个
  • linux---线程池种类以及实现(固定数量)

    线程池是什么 一堆固定的数量的或者有最大数量限制的线程 43 任务队列 gt 用于我们并发处理请求 xff0c 避免了大量频繁的线程的创建和销毁的事件成本 xff0c 同时避免了峰值压力带来瞬间大量线程被创建资源耗尽 xff0c 程序奔溃的
  • 什么是线程池?为什么使用线程池?

    1 什么是线程池 xff1f 线程池和数据库连接池非常类似 xff0c 可以统一管理和维护线程 xff0c 减少没有必要的开销 2 为什么要使用线程池 xff1f 因为频繁的开启线程或者停止线程 xff0c 线程需要重新从cpu从就绪状态调
  • Java实现List按条件分成多个子List

    一 业务场景 相信很多开发的小伙伴都有遇到过需要对表按特定条件进行查询 xff0c 然后再进行归类 xff0c 比如 xff1a 对员工表进行检索 xff0c 然后分别按他们所在的部门进行归类 xff0c 一般的做法都是按部门唯一标识 xf
  • MySQL生成随机姓名

    CREATE DEFINER 61 96 root 96 64 96 localhost 96 FUNCTION 96 rand name 96 n int RETURNS varchar 16 CHARSET utf8 begin 初始化
  • RabbitMQ的安装教程

    本文介绍RabbitMQ在Linxu上的安装教程 一 下载相关安装包 相应的安装包可以从官网上 xff08 https www rabbitmq com xff09 进行下载 xff0c 也可以从我的网盘上下载 蓝奏云地址 xff1a ht
  • SpringBoot实现广州健康通疫苗预约提醒

    一 前言 终于轮到了打第二针疫苗的时候 xff0c 无奈每次打开 广州健康通 或 粤康通 小程序 xff0c 每次都是被预约完的状态 xff0c 广州人口众多 xff0c 说不定有很多人一直守在小程序前等着放号 xff0c 所以这篇文章就诞
  • 搭建SFTP服务器实现文件上传

    1 前言 最近一直在做数据迁移接口的开发 xff0c 涉及到大文件的远程下载与上传 xff0c 其实倒没有什么原理可言 xff0c 无非就是两台机器互连之后 xff0c 获得文件流然后进行传输 xff0c 不过在这过程也遇到过一些小坑 xf
  • SpringBoot整合RabbitMQ实现五种消息模型

    一 什么是消息队列 xff1f 消息 xff0c 可以理解为两个应用之间传递的数据 xff0c 数据可以是基本数据类型 xff0c 也可以是对象等 消息队列 xff0c 则是容器 xff0c 生产者产生的消息存放在这个容器里面 MQ的整个过
  • SpringBoot整合CXF框架实现Webservice服务端

    1 前言 近期接手一个10多年的老项目 xff0c 敲重点 xff0c 10多年 xff01 xff01 xff01 就是最纯粹的servlet技术 xff0c 貌似是从2008年运维到现在 xff0c 老项目终究会有被淘汰的这一天 xff
  • Windows下切换不同版本JDK

    1 前言 从四月份重新入职新公司以来 xff0c 主要负责两个项目的开发 xff0c 一个是10多年前的项目 xff0c 一个是2019年开始开发的项目 xff0c 这两个项目依赖于不同版本的JDK xff0c 一个是JDK6 xff0c
  • css实现圆形div旋转,如“已预约”效果

    lt DOCTYPE html gt lt html gt lt head gt lt meta charset 61 34 utf 8 34 gt lt title gt lt title gt lt head gt lt style g
  • c++---类和对象(六大默认成员函数)

    类中默认的六个成员函数构造函数析构函数拷贝构造函数赋值操作符重载取地址和const取地址操作符重载const成员函数 1 类中默认的六个成员函数 首先看看下面代码 class A int main A a return 0 这个代码并没有报
  • 微服务系列--nacos注册中心与服务发现

    1 前言 终究还是到了更新关于微服务相关博客的时候了 xff0c 经过挺长一段时间微服务的自主学习 xff0c 现在不敢说自己熟悉微服务 xff0c 但我也能略知一二 微服务嘛 xff0c 其实入门之后便会发现 xff0c 其实关于微服务相