欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringCloud之 Ribbon

程序员文章站 2022-06-22 16:17:48
...

UserController

@RestController
public class UserController {
  @Autowired
  private UserRepository userRepository;
  @Autowired
  private Registration registration;

  @GetMapping("/{id}")
  public User findById(@PathVariable Long id) {
    User findOne = userRepository.findOne(id);
    return findOne;
  }

  @GetMapping("/getIpAndPort")
  public String findById() {
      return registration.getHost() + ":" + registration.getPort();
  }
}

user服务提供者,配置

server:
  port: 8001
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

服务消费者order

server:
  port: 8010
spring:
  application:
    name: microservice-consumer-order
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

启动类
@LoadBalanced

@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerOrderApplication {
  @Bean
  @LoadBalanced
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }

  public static void main(String[] args) {
    SpringApplication.run(ConsumerOrderApplication.class, args);
  }
}

调用user

@RestController
public class OrderController {
  private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.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("/user/getIpAndPort")
  public String getIpAndPort() {
      return this.restTemplate.getForObject("http://microservice-provider-user/getIpAndPort", String.class);
  }

  @GetMapping("/user1/getIpAndPort")
  public String getUserIpAndPort() {
      return this.restTemplate.getForObject("http://microservice-provider-user222/getIpAndPort", String.class);
  }

  @GetMapping("/log-user-instance")
  public void logUserInstance() {
    ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user");
    // 打印当前选择的是哪个节点
    OrderController.LOGGER.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort());
  }
}
/**
 * 使用RibbonClient,为特定name的Ribbon Client自定义配置.
 * 使用@RibbonClient的configuration属性,指定Ribbon的配置类.
 */
@Configuration
@RibbonClient(name = "microservice-provider-user", 
configuration = RibbonConfiguration.class)
public class ProviderUserConfiguration {}
/**
 * 该类为Ribbon的配置类
 * 注意:该类不应该在主应用程序上下文的@ComponentScan 中。
 */
@Configuration
public class RibbonConfiguration {
  @Bean
  public IRule ribbonRule() {
    // 负载均衡规则,改为随机
    return new RandomRule();
  }
}

包结构图
SpringCloud之 Ribbon

配置负载均衡策略

server:
  port: 8010
spring:
  application:
    name: microservice-consumer-order
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

microservice-provider-user:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

ribbon脱离eureka实现负载均衡

 <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
    </dependency>
server:
  port: 8010
spring:
  application:
    name: microservice-consumer-order
microservice-provider-user:
  ribbon:
    listOfServers: localhost:8001,localhost:8002
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

SpringCloud之 Ribbon

SpringCloud之 Ribbon