SpringCloud - Ribbon负载均衡

  Eureka和Ribbon结合使用的时,Ribbon自动从Eureka server获取服务提供者地址列表,并基于负载均衡算法,请求其中一个服务提供者实例;Ribbon会自动将虚拟主机名映射到微服务的网络地址。
 
 
一. Eureka管理服务
  • 启动microserver-discovery-eureka
  • 启动2个或多个microserver-provider-user
  • 启动microserver-consumer-movie-ribbon
  1.服务集群
  定义一个服务集群,将服务提供者和消费者注册到服务集群:microserver-discovery-eureka
server:
  port: 8761                    # 指定该Eureka实例的端口
eureka:
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
 
  2.服务提供者
  编码业务逻辑,注册到服务集群,并启动多个服务提供者:microserver-provider-user
server:
  port: 8000
spring:
  application:
    name: microservice-provider-user
  jpa:
    generate-ddl: false
    show-sql: true
    hibernate:
      ddl-auto: none
  datasource:                           # 指定数据源
    platform: h2                        # 指定数据源类型
    schema: classpath:schema.sql        # 指定h2数据库的建表脚本
    data: classpath:data.sql            # 指定h2数据库的数据脚本
logging:                                # 配置日志级别,让hibernate打印出执行的SQL
  level:
    root: INFO
    org.hibernate: INFO
    org.hibernate.type.descriptor.sql.BasicBinder: TRACE
    org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
java -jar microservice-provider-user-0.0.1-SNAPSHOT.jar --server.port=8000
java -jar microservice-provider-user-0.0.1-SNAPSHOT.jar --server.port=8001
 
  3.服务消费者
  服务消费者注册到集群,定义Ribbon负载均衡功能,启动一个服务消费者:microserver-consumer-movie-ribbon,Ribbon可自动从Eureka server获取服务提供者列表,并基于负载均衡算法,请求其中一个服务提供者实例。
  注册到集群
server:
  port: 8010
spring:
  application:
    name: microservice-consumer-movie
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
   定义负载均衡的ReatTemplate
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerMovieApplication {
  @Bean
  @LoadBalanced
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }
 
  public static void main(String[] args) {
    SpringApplication.run(ConsumerMovieApplication.class, args);
  }
}
 
  服务消费者使用负载均衡的RestTemplate访问服务提供者
@RestController
public class MovieController {
  private static final Logger LOGGER = LoggerFactory.getLogger(MovieController.class);
 
  @Autowired
  private RestTemplate restTemplate;
  @Autowired
  private LoadBalancerClient loadBalancerClient;
 
  @GetMapping("/user/{id}")
  public User findById(@PathVariable Long id) {
    return this.restTemplate.getForObject("http://microservice-provider-user/" + id, User.class);
  }
 
  @GetMapping("/log-user-instance")
  public void logUserInstance() {
    ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user");
    // 打印当前选择的是哪个节点
    MovieController.LOGGER.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort());
  }
}
 
二. 配置Ribbon负载均衡规则
  1.Java配置
  定义负载均衡的规则,然后设置到客户端(注意:RibbonConfiguration不能定义在@SpringBootApplication的作用范围内):
@Configuration
public class RibbonConfiguration {
    @Bean
    public IRule ribbonRule() {
        // 负载均衡规则,改为随机
        return new RandomRule();
    }
}
 
@Configuration
@RibbonClient(name = "microservice-provider-user", configuration = RibbonConfiguration.class)
public class TestConfiguration {
}
  2.属性配置
 
  在application.yml中添加属性:
microservice-provider-user:
    ribbon:
        NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
 
三. 脱离Eureka使用Ribbon
  1.去掉Eureka的依赖,修改为Ribbon,删除@EnableaDiscoveryClient注解:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
   
  2.将application.yml改为如下:
server:
    port: 8010
spring:
    application:
        name: microservice-consumer-movie
microservice-provider-user:
    ribbon:
        listOfServers: localhost:8000,localhost:8001
 
 
Feign超时:
feign:
client:
config:
default:
connectTimeout: 1000
readTimeout: 1000

    @Bean
    Request.Options feignOptions() {
        return new Request.Options(/**connectTimeoutMillis**/1 * 1000, /** readTimeoutMillis **/1000 * 1000);
    }
posted @ 2018-02-08 22:42  liguochun  阅读(200)  评论(0编辑  收藏  举报