SpringCloud第四篇 ribbon
1.複製上一個專案eureka-client,命名為eureka-client2,並修改pom.xml對應的名字,修改applicaiton.yml裡面的埠為8002,application name不換
2.啟動eureka,兩個client
3.新建一個專案 ribbon-client
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.star.guo</groupId>
<artifactId>springcloudversion</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<!-- <groupId>com.star.guo</groupId> -->
<artifactId>ribbon-client</artifactId>
<!-- <version>0.0.1-SNAPSHOT</version> -->
<packaging>jar</packaging>
<name>ribbon-client</name>
<description>Spring Cloud專案</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
5.核心配置檔案修改application.yml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8000/eureka/
server:
port: 8003
spring:
application:
name: ribbon-client
6.添加註解和register bean
@EnableEurekaClient
@EnableDiscoveryClient
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
效果如下圖
7.新建一個Conroller測試兩個eureka-client
package com.star.guo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* 訊息Controller,使用ribbon測試叢集效果
* @author Star.Guo
*
*/
@RestController
public class MessageController {
@Autowired
RestTemplate restTemplate;
/**
* 呼叫的服務名
*/
private static final String serviceName = "EUREKA-CLIENT";
/**
* Hello方法
* @param user 使用者名稱
* @return String
*/
@GetMapping
public String hello(String user) {
return restTemplate.getForObject("http://" + serviceName + "/hi?user=" + user, String.class);
}
}
8.啟動並訪問測試
http://localhost:8003/?user=yourname
如果交替輸出下面結果則正確(重新整理頁面一次切換一次)
hello yourname current port is:8001
hello yourname current port is:8002