Nacos服务注册与发现

安装Nacos

  • 下载二进制包

    下载地址

  • 解压

    unzip nacos-server-1.0.0.zip
    cd nacos/bin 
    
  • 启动

    sh startup.sh -m standalone
    
  • 打开登陆地址

    http://localhost:8848/nacos/
    

添加Spring Cloud Alibaba依赖


        
            
            
                org.springframework.boot
                spring-boot-dependencies
                2.1.2.RELEASE
                pom
                import
            
            
            
                org.springframework.cloud
                spring-cloud-dependencies
                Greenwich.SR2
                pom
                import
            
            
            
                com.alibaba.cloud
                spring-cloud-alibaba-dependencies
                2.1.0.RELEASE
                pom
                import
            
        
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

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

编写服务提供者

@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosDiscoveryProviderApplication.class, args);
    }


    @GetMapping("/hello")
    public String hello(){
        return "hello nacos-discovery-provider";
    }
}

配置注册到Nacos

server:
  port: 8085
spring:
  application:
    name: nacos-discovery-provider
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

看到日志

2020-10-10 23:14:10.152  INFO 54121 --- [           main] c.a.c.n.registry.NacosServiceRegistry    : nacos registry, nacos-discovery-provider 192.168.0.105:8085 register finished

表示已经成功注册到nacos,如图:

nacos注册服务者

编写消费者代码

@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosDiscoveryConsumerApplication.class, args);
    }

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

使用Ribbon做客户端负载均衡调用服务者

@RestController
public class HelloController {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    LoadBalancerClient loadBalancerClient;

    @GetMapping("/hello")
    public String HelloClient(String name){
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-discovery-provider");
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "hello?name=" + name, String.class);
    }
}

配置文件与服务端类似

server:
  port: 18085
spring:
  application:
    name: nacos-discovery-consumer
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

两者都成功注册到Nacos里

image-20201011102305466

调用消费者/hello服务,可以调用Provider提供的服务

image-20201011102401045

你可能感兴趣的:(Nacos服务注册与发现)