服务发现-Nacos

 

1.搭建Nacos Server:

   1.下载 Nacos 

              地址: https://github.com/alibaba/nacos/releases

下载 1.0.1 版本

  2.搭建 Nacos Server

        文档:https://nacos.io/zh-cn/docs/quick-start.html

我是windows 电脑:

     使用cmd 命令: 在E:\Nacos\nacos\bin 目录下

扫描二维码关注公众号,回复: 12922355 查看本文章

执行: startup.cmd -m standalone

访问地址:

192.168.10.x 是我本机的IP地址,8848 是默认端口号

当然也可以是:   http://localhost:8848/nacos/index.html#/login

登陆名 和密码 都是  nacos

2. 将应用注册到 Nacos:

1.在pom中添加依赖:

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

2. application.yml 添加配置:

注意 : 是 spring.cloud

3. 然后 maven install 一下:

在nacos server 中显示:

3.客户端总是能找到消费端:

     1.首先在controller层使用:

@Autowired
private DiscoveryClient discoveryClient;
   /*

    证明 用户中心总能找到服务中心
*/
   @GetMapping("/test2")
   public List<ServiceInstance> getInstance(){
       return discoveryClient.getInstances("user-center");
   }

当然 服务中心也可以找到 用户中心

4. 引入服务发现:

 之前使用  RestTemplate  调用 另一个服务的方法,但是 URL 是写死的,这样是极不合理的,

1.注入 DiscoveryClient

2. 拿到用户中心所有实例的信息

List<ServiceInstance> instances = discoveryClient.getInstances("user-center");
String targetUrl =instances.stream().map(instance ->
        instance.getUri().toString()+"/users/{id}")
        .findFirst().orElseThrow(()->new IllegalArgumentException("当前没有实例"));
  log.info(targetUrl);

 

5.  服务发现的领域模型:

1. namespace(命名空间) 主要用于 隔离 环境: 比如 : 生产,开发,测试 环境,就可以创建三个 namespace,互不影响。

2. group : 可以将不同的微服务 划分到 同一分组中,方便管理。

3. service : 微服务,比如 :用户微服务,内容微服务 ,一个service可以包含多个集群(cluster)

猜你喜欢

转载自blog.csdn.net/weixin_42528855/article/details/115035472