使用Ribbon实现Eureka的负载均衡

朴灿烈づ我的快乐病毒、 2022-12-21 02:23 174阅读 0赞

本篇接于《SpringBoot:Eureka搭建注册中心》和《SpringBoot:Eureka创建服务消费者》。

  • pom文件



    org.springframework.cloud
    spring-cloud-starter-netflix-eureka-client



    org.springframework.cloud
    spring-cloud-starter-netflix-ribbon



    org.springframework.boot
    spring-boot-starter-web



    org.springframework.boot
    spring-boot-starter-actuator

  • Application

    @SpringBootApplication
    @EnableDiscoveryClient
    public class RibbonConsumerApplication {

    1. @Bean
    2. @LoadBalanced
    3. public RestTemplate template() {
    4. return new RestTemplate();
    5. }
    6. public static void main(String[] args) {
    7. new SpringApplicationBuilder(RibbonConsumerApplication.class)
    8. .web(WebApplicationType.SERVLET)
    9. .run(args);
    10. }

    }

  • 配置文件

    eureka:
    client:

    1. serviceUrl:
    2. defaultZone: http://localhost:20000/eureka/

    server:
    port: 31000
    spring:
    application:

    1. name: ribbon-consumer
  • 测试Controller

    @RestController
    public class Controller {

    1. @Autowired
    2. private RestTemplate restTemplate;
    3. @GetMapping("/sayHi")
    4. public String sayHi() {
    5. return restTemplate.getForObject(
    6. "http://eureka-client/sayHi",
    7. String.class);
    8. }

    }

我们EurekaServer,并在30001和30002两个端口上启动两个client,同时启动Ribbon
在这里插入图片描述
然后我们使用postman请求localhost:31000/sayHi接口,可以看到多次请求,返回结果会This is 30001This is 30002
在这里插入图片描述
在这里插入图片描述
说明@LoadBalanced注解已经生效了!

发表评论

表情:
评论列表 (有 0 条评论,174人围观)

还没有评论,来说两句吧...

相关阅读

    相关 eurekaribbon负载均衡

    接着上一篇博文,看下ribbon的负载均衡 重点,ribbon的负载均衡功能 改造上一篇博文的内容,服务注册中心的端口号修改为5550 服务提供者,修改端口号为5551,