springcloudAlibaba整合nacos
1、添加依赖
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>${latest.version}</version> </dependency>
注意:版本 2.1.x.RELEASE 对应的是 Spring Boot 2.1.x 版本。版本 2.0.x.RELEASE 对应的是 Spring Boot 2.0.x 版本,版本 1.5.x.RELEASE 对应的是 Spring Boot 1.5.x 版本。
2、配置文件application.properties
server:
port: 8082
spring:
cloud:
nacos:
discovery:
server-addr: 192.168.123.101:8848,192.168.123.101:8849,192.168.123.101:8850
namespace: nacos-dev
application:
name: nacos-demo01
3、添加注解
通过 Spring Cloud 原生注解 @EnableDiscoveryClient
开启服务注册发现功能
@SpringBootApplication @EnableDiscoveryClient public class NacosProviderApplication { public static void main(String[] args) { SpringApplication.run(NacosProviderApplication.class, args); } @RestController class EchoController { @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET) public String echo(@PathVariable String string) { return "Hello Nacos Discovery " + string; } } }
4、通过 Spring Cloud 原生注解 @EnableDiscoveryClient
开启服务注册发现功能
给 RestTemplate 实例添加 @LoadBalanced
注解,开启 @LoadBalanced
与 Ribbon 的集成:
@SpringBootApplication @EnableDiscoveryClient public class NacosConsumerApplication { @LoadBalanced @Bean public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(NacosConsumerApplication.class, args); } @RestController public class TestController { private final RestTemplate restTemplate; @Autowired public TestController(RestTemplate restTemplate) {this.restTemplate = restTemplate;} @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET) public String echo(@PathVariable String str) { return restTemplate.getForObject("http://service-provider/echo/" + str, String.class); } } }
5、springCloudAlibaba和nacos,springboot版本说明
Spring Cloud Version | Spring Cloud Alibaba Version | Spring Boot Version |
---|---|---|
Spring Cloud 2020.0.1 |
2021.1 |
2.4.2 |
Spring Cloud Hoxton.SR9 |
2.2.6.RELEASE |
2.3.2.RELEASE |
Spring Cloud Greenwich.SR6 |
2.1.4.RELEASE |
2.1.13.RELEASE |
Spring Cloud Hoxton.SR3 |
2.2.1.RELEASE |
2.2.5.RELEASE |
Spring Cloud Hoxton.RELEASE |
2.2.0.RELEASE |
2.2.X.RELEASE |
Spring Cloud Greenwich |
2.1.2.RELEASE |
2.1.X.RELEASE |
Spring Cloud Finchley |
2.0.4.RELEASE(停止维护,建议升级) |
2.0.X.RELEASE |
Spring Cloud Edgware |
1.5.1.RELEASE(停止维护,建议升级) |
1.5.X.RELEASE |
6、命名空间
查看地址:https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E
参考地址:https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme.md