各个章节可能有关联关系,查找《SpringCloud实战教程》其他章节请参考:
http://www.yayihouse.com/yayishuwu/book/79
6. Springcloud通过ribbon负载均衡调用其他服务接口示例教程
(0) 在前面章节《idea创建springcloud服务提供者工程euraka-client》所创建的项目中添加以下服务接口给ribbon客户端消费调用。
@RequestMapping("/getPort")
@ResponseBody
public String getPort(HttpServletRequest request){
return "服务的端口:"+request.getServerPort();
}
(1) 右键刚刚创建好的工程--》New--》Module--》Spring Initializr--》next--》修改一下Group为com.wlg.springcloud和Artifact为eureka-client-ribbon--》next--》Spring Cloud Routing--》勾选Ribbon(Maintenance) --》 next--》Finish。
(2) 启动类上加上@EnableDiscoveryClient注解
@SpringBootApplication
@EnableDiscoveryClient
public class EurekaClientRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientRibbonApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
(3) 把application.properties改为application.yml,内容如下:
server:
port: 9904
spring:
application:
name: service-four
eureka:
client:
serviceUrl:
defaultZone: http://localhost:9901/eureka/
instance:
prefer-ip-address: true
(4) 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.wlg.springcloud</groupId>
<artifactId>springcloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.wlg.springcloud</groupId>
<artifactId>eureka-client-ribbon</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eureka-client-ribbon</name>
<description>Demo project for Spring Boot</description>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
</project>
(5) Ribbon通过restTemplate调用服务的代码:
@RestController
public class RibbonClientController {
@Autowired
RestTemplate restTemplate;
@RequestMapping("/getPort")
public void getPort(HttpServletResponse response) throws IOException {
final String result = restTemplate.getForObject("http://SERVICE-ONE/getPort", String.class);
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter writer = response.getWriter();
writer.print(result);
writer.flush();
writer.close();
}
}
(6) 测试要结合前面几章来联合测试,分别启动注册中心eureka-server、eureka-client(端口分别修改为9902和9903并分别启动)和现在的eureka-client-ribbon,浏览器访问注册中心服务:http://localhost:9901/就可以看到服务提供者service-one(两个端口两个服务)和service-four已经注册到注册中心了。
在浏览器地址栏输入:http://localhost:9904/getPort
浏览器就会显示不同结果:
有时是:服务的端口:9903 有时是:服务的端口:9902
这个就说明ribbon通过轮询的方式调用注册中心中其他服务接口成功