Spring Cloud Alibaba Nacos服务注册与发现

1.什么是Nacos

Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。

Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施。

Nacos官方文档

2.准备工作

下载nacos-server

启动

sh startup.sh -m standalone

Nacos默认控制台访问地址:http://localhost:8848
默认账号密码都是:nacos

3.服务注册

引入依赖

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

applicaiton.yml

server:
  port: 8000
  
spring:
  application:
    # 默认使用${spring.application.name}作为注册服务的名称
    name: nacos-provider
  cloud:
    nacos:
      discovery:
        # nacos-server地址
        server-addr: localhost:8848

使用 @EnableDiscoveryClient 注解开启服务注册与发现

@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class NacosProviderApplication {

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

    @GetMapping("hello")
    public String hello(){
        return "hello";
    }
}

4.服务发现

application.yml

server:
  port: 8010

spring:
  application:
    name: nacos-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848

RestTemplate

  1. 添加 @LoadBlanced 注解,使得 RestTemplate 接入 Ribbon
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
	return new RestTemplate();
}
  1. controller
@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("hello-rest")
    public String rest(){
        return restTemplate.getForObject("http://nacos-provider/hello", String.class);
    }
}
  1. 测试
    curl http://localhost:8010/hello-rest
    hello

FeignClient

  1. 引入依赖
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  1. 使用@EnableFeignClients开启FeignClient
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class NacosConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(NacosConsumerApplication.class, args);
    }
}
  1. FeignClient
// 调用服务的名称
@FeignClient("nacos-provider")
public interface TestFeign {
    // 调用服务的接口
    @GetMapping("/hello")
    String hello();
}
  1. controller
@Autowired
    private TestFeign testFeign;

    @GetMapping("hello-feign")
    public String feign(){
        return testFeign.hello();
    }
  1. 测试
    curl http://localhost:8010/hello-feign
    hello

示例代码

作者博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值