一、搭建一個或以上的EurekaServer(本文以兩個爲例)
- 添加Eureke-Server依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- 添加註解
@EnableEurekaServer
@SpringBootApplication
@EnableEurekaServer
public class EurekaServer01Application {
public static void main(String[] args) {
SpringApplication.run(EurekaServer01Application.class, args);
}
}
- 添加配置
#設置服務端口,eureka server端默認端口是8761
spring:
application:
name: eureka-server
#設置服務端口,eureka server端默認端口是8761
server:
port: 8000
#表示是否將自己註冊到Eureka Server,默認爲true
eureka:
client:
register-with-eureka: true
#表示是否從Eureka Server獲取註冊信息,默認爲true
fetch-registry: true
#暴露給其他eureka client端註冊的地址
service-url.defaultZone: http://localhost:8001/eureka/
4. 依據以上步驟再搭建一個EurekaServer注意修改端口號,注意spring.application.name=eureka-server保持一致
二、搭建三個Provider節點
- 啓動類
@SpringBootApplication
@EnableDiscoveryClient
public class ProviderRibbon01Application {
public static void main(String[] args) {
SpringApplication.run(ProviderRibbon03Application.class, args);
}
}
- 配置文件
spring:
application:
name: provider-ribbon
server:
port: 10002
eureka:
client:
service-url.defaultZone: http://localhost:8000/eureka/,http://localhost:8001/eureka/
- 按照以上步驟繼續搭建兩個及以上,注意
spring.application.name=provider-ribbon
保持一致
三、搭建Consumer節點
- 添加Ribbon依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
- 添加配置類
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RetryRule;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
1. @author Eden
2. @date 2020/5/1 10:17
*/
@Configuration
public class RibbonConfig {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
/**
* Ribbon默認負載均衡策略是輪詢,現在將其改爲隨機
* @return
*/
@Bean
public IRule demoRule(){
return new RetryRule();
}
}
demo代碼
主要是以下幾個模塊
拓展
- Ribbon原理示意圖