一、搭建一个或以上的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原理示意图