1.什么是Nacos
Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。
Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施。
2.准备工作
启动
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
- 添加 @LoadBlanced 注解,使得 RestTemplate 接入 Ribbon
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
- controller
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("hello-rest")
public String rest(){
return restTemplate.getForObject("http://nacos-provider/hello", String.class);
}
}
- 测试
curl http://localhost:8010/hello-rest
hello
FeignClient
- 引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 使用@EnableFeignClients开启FeignClient
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class NacosConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(NacosConsumerApplication.class, args);
}
}
- FeignClient
// 调用服务的名称
@FeignClient("nacos-provider")
public interface TestFeign {
// 调用服务的接口
@GetMapping("/hello")
String hello();
}
- controller
@Autowired
private TestFeign testFeign;
@GetMapping("hello-feign")
public String feign(){
return testFeign.hello();
}
- 测试
curl http://localhost:8010/hello-feign
hello