二、集成注册中心nacos

一、版本选择

官方版版本说明 · alibaba/spring-cloud-alibaba Wiki · GitHub

image.png

我们需要选择2.2.7对应的这一排组件版本,因此nacos应该选2.0.3

二、集成nacos

第一步:下载nacos-server

下载地址: Release 2.0.3 (July 28, 2021) · alibaba/nacos · GitHub

第二步:解压并启动nacos-server,window执行bin目录下的startup.cmd文件。

注意:执行前需编辑startup.cmd文件,将MODE的值修改为standalone,否则会报错。

启动成功,访问http://localhost:8848/nacos,账户密码都是nacos

image.png

第三步:代码集成nacos

给三个模块进入nacos依赖

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

添加配置

spring:
  cloud:
    nacos:
      discovery:
        # 指定nacos server的地址
        server-addr: localhost:8848

第四步:启动各模块,查看nacos-server页面

image.png

第五步:测试能否通过注册中心找到微服务

编写代码

package com.badcat.a.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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author 50244
 */
@RestController
@RequestMapping("/nacos")
public class TestNacosController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/nacos_intstance/{instanceId}")
    public List<ServiceInstance> getNacosIntstance(@PathVariable String instanceId){
        return this.discoveryClient.getInstances(instanceId);
    }
}

如下图,可以获取module-b的信息

image.png

第六步:module-a调用module-b

编写代码

    @GetMapping("/let_module-b_say_hello")
    public String letModuleBSayHello(){
        List<ServiceInstance> list_b = this.discoveryClient.getInstances("b");
        ServiceInstance b = list_b.get(0);
        String uri = b.getUri().toString();
        String result = restTemplate.getForObject(uri + "/hello/say_hello", String.class);
        log.info("module-b say : [{}]", result);
        return String.format("module-b say : [%s]", result);
    }

调用结果如下

image.png

这部分代码放到了码云 study_badcat/spring-cloud-alibaba-study (gitee.com)
,v2.0分支

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容