Nacos用于发现、配置和管理微服务,提供一组简单易用的特性集,可以快速实现动态服务发现、服务配置、服务元数据及流量管理,Nacos实现服务远程调用,常用的方法是RestTemplate结合@LoadBalanced和Feign
版本说明
2021.x 分支对应的是 Spring Cloud 2021 与 Spring Boot 2.6.x,最低支持 JDK 1.8
2020.0 分支对应的是 Spring Cloud 2020 与 Spring Boot 2.4.x,最低支持 JDK 1.8
2.2.x 分支对应的是 Spring Cloud Hoxton 与 Spring Boot 2.2.x,最低支持 JDK 1.8
更多版本说明请参阅官网
特别说明:需要提前安装好nacos服务器
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
dependencies>
server:
port: 8100
spring:
application:
name: alibaba-service-provider
cloud:
nacos:
discovery:
server-addr: XX.XX.XX.XX:8848
enabled: true
username: nacos
password: nacos
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceProviderApplication.class, args);
}
}
@RestController
@RequestMapping("/service")
public class ServiceProviderController {
private static final Logger logger = LoggerFactory.getLogger(ServiceProducerController.class);
@GetMapping("/getServiceInfo")
private String getServiceInfo() {
logger.info("远程接口调用提供方,当前时间为:{}", LocalDateTime.now());
return "This is service provider,now is:" + LocalDateTime.now();
}
}
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
dependencies>
server:
port: 8101
spring:
application:
name: alibaba-ribbon-consumer
cloud:
nacos:
discovery:
server-addr: xx.xx.xx.xx:8848
fail-fast: true
username: nacos
password: nacos
management:
endpoints:
web:
exposure:
include: '*'
@SpringBootApplication
@EnableDiscoveryClient
public class RibbonConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonConsumerApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@RestController
@RequestMapping("/ribbon")
public class RibbonConsumerController {
private static final Logger logger = LoggerFactory.getLogger(RibbonConsumerController.class);
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/getServiceInfoForUrl")
public String getServiceInfoForUrl() {
List<ServiceInstance> instances = discoveryClient.getInstances("alibaba-service-provider");
int index = new Random().nextInt(instances.size());
ServiceInstance serviceInstance = instances.get(index);
String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
logger.info("从nacos中获取到的微服务地址为:", url);
return restTemplate.getForObject("http://" + url + "/service/getServiceInfo", String.class);
}
}
在浏览器输入http://localhost:8101/ribbon/getServiceInfoForUrl
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-loadbalancerartifactId>
dependency>
注意:新版本中必须要引入spring-cloud-starter-loadbalancer依赖,否则会报java.net.UnknownHostException异常
在主启动类中的restTemplate()方法上添加@LoadBalanced注解
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@GetMapping("/getServiceInfo")
public String getServiceInfo() {
return restTemplate.getForObject("http://alibaba-service-provider/service/getServiceInfo", String.class);
}
在浏览器输入地址http://localhost:8101/ribbon/getServiceInfo
新建一个springboot项目,引入核心依赖
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-loadbalancerartifactId>
dependency>
dependencies>
server:
port: 8102
spring:
application:
name: alibaba-openfeign-consumer
cloud:
nacos:
discovery:
server-addr: xx.xx.xx.xx:8848
fail-fast: true
username: nacos
password: nacos
management:
endpoints:
web:
exposure:
include: '*'
logging:
level:
com.xlhj.cloud.alibaba.service.ProviderService: debug
@Configuration
public class OpenFeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
配置日志等级
public class ProviderServiceFallback implements ProviderService {
@Override
public String getServiceInfo() {
return "get service info fallback!";
}
}
@FeignClient(value = "alibaba-service-provider", fallback = ProviderServiceFallback.class, configuration = OpenFeignConfig.class)
public interface ProviderService {
@GetMapping(value = "/service/getServiceInfo")
String getServiceInfo();
}
@RestController
@RequestMapping("/openfeign")
public class OpenFeignConsumerController {
private static final Logger logger = LoggerFactory.getLogger(OpenFeignConsumerApplication.class);
@Autowired
private ProviderService providerService;
@GetMapping("/getServiceInfo")
public String getServiceInfo() {
String serviceInfo = providerService.getServiceInfo();
logger.info("openfeign调用远程接口返回为:{}", serviceInfo);
return serviceInfo;
}
}