上一篇:Spring Cloud Alibaba学习(三):服务提供者
下一篇:Spring Cloud Alibaba学习(五):服务消费者-Feign
创建子模块consumer
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-alibaba-icydate</artifactId>
<groupId>com.icydate</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>consumer</artifactId>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Spring Boot Begin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot End -->
<!-- Spring Cloud Begin -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Spring Cloud End-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.icydate.ConsumerApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
application:
name: icydate-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
server:
port: 8081
SpringBoot启动类
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
RestTemplate
创建名为RestTemplateConfig的配置类,用于提供RestTemplate,用于发起HTTP请求
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
接口
@RestController
public class NacosConsumerController {
# 负载均衡
@Autowired
private LoadBalancerClient loadBalancerClient;
@Autowired
private RestTemplate restTemplate;
// 取出应用名,传递给Provider
@Value("${spring.application.name}")
private String caller;
@GetMapping(value = "/call/provider")
public String callProvider() {
# 选择要访问的提供者
ServiceInstance serviceInstance = loadBalancerClient.choose("icydate-provider");
# 通过获得的服务实例,拼接url
String url = String.format("http://%s:%s/get/%s", serviceInstance.getHost(), serviceInstance.getPort(), caller);
return restTemplate.getForObject(url, String.class);
}
}
目录结构
启动项目后,会看到consumer也被注册到了Nacos里
访问consumer的/call/provider接口,得到下面的返回
负载均衡
由于使用了LoadBalancer,我们可以点击edit configurations,勾选ProviderApplication的Allow parallel run来允许并行启动Provider
修改端口后再次启动,可以看到Provider的实例变为了两个
此时重复访问Consumer的/call/provider,会进行负载均衡,Consumer能够访问到不同端口的Provider