负载均衡Ribbon的使用

(1)在pom.xml中导入ribbon的依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

(2)在application.yml文件中开始ribbon服务

#允许使用ribbon
ribbon:
  eureka:
    enabled: true

(3)调用restTemplate的时候加一个负载均衡的注解:

@Bean
@LoadBalanced
public RestTemplate get(){
    return new RestTemplate();
}

(4)在引导类上添加Ribbon客户端的注解

@SpringBootApplication
@RibbonClients
public class UserConsumer9001Application {

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

(5)开启测试,Ribbon所指定的策略就是轮询,同时也可以修改当前的策略,具体修改步骤省略了。但是在服务消费方此时要根据服务名来调提供者的服务了.

 String baseUrl = "http://service-provider/user/" + id;
 return this.restTemplate.getForObject(baseUrl, String.class);
发布了52 篇原创文章 · 获赞 74 · 访问量 6366

猜你喜欢

转载自blog.csdn.net/qq_39182939/article/details/104609176