微服务组件:负载均衡Ribbon

微服务组件:负载均衡Ribbon

 1. Ribbon介绍

       在微服务中,通常一个应用系统需要部署多个实例,分布在不同的运行容器中。为了避免所有的请求,都集中在一台机器,使请求均匀分布在多个实例应用系统上,这时候就需要用到负载均衡组件Ribbon。

 

2. Ribbon使用

2-1 启动eureka注册中心

 

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {

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

 

 启动springboot-eureka-peer1

server.port=8761

spring.application.name=springboot-eureka-peer1

eureka.instance.hostname=localhost
eureka.client.serviceUrl.defaultZone=http://localhost:8762/eureka/,http://localhost:8761/eureka/

 

 启动springboot-eureka-peer2

server.port=8762

spring.application.name=springboot-eureka-peer2

eureka.instance.hostname=localhost
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/,http://localhost:8762/eureka/

 


 

2-2 启动服务提供者

 

java -jar -Dserver.port=8071 microservice-provider-user-0.0.1-SNAPSHOT.jar
java -jar -Dserver.port=8072 microservice-provider-user-0.0.1-SNAPSHOT.jar

 

 

 

 

2-3 查看服务注册情况

http://mengka-host.local:8762/

 



 

 

2-4 启动服务调用客户端

/**
   * 实例化RestTemplate,通过@LoadBalanced注解开启均衡负载能力.
   * @return restTemplate
   */
  @Bean
  @LoadBalanced
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }

 

@Service
public class RibbonService {
  @Autowired
  private RestTemplate restTemplate;

  public User findById(Long id) {
    // http://服务提供者的serviceId/url
    return this.restTemplate.getForObject("http://microservice-provider-user/" + id, User.class);
  }
}

 

eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/,http://localhost:8762/eureka/

 

2-5 调用findById接口服务

http://127.0.0.1:8010/ribbon/1

服务调用均衡分布在2台服务提供者机器上:



 

3. Feign使用

     Feign是一种声明式、模板化的HTTP客户端,spring cloud为Feign添加了注解支持,并整合了Ribbon和Eureka提供负载均衡,使得编写服务调用客户端更为容易。

3-1 启动服务调用客户端

使用@EnableFeignClients开启Feign

@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class MovieFeignApplication {
  public static void main(String[] args) {
    SpringApplication.run(MovieFeignApplication.class, args);
  }
}
 

服务调用接口

@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping("/{id}")
  public User findByIdFeign(@RequestParam("id") Long id);
}
 
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/,http://localhost:8762/eureka/
 

3-2 调用findById接口服务

http://127.0.0.1:8020/feign/2

服务调用均衡分布在2台服务提供者机器上:

 

猜你喜欢

转载自hyy044101331.iteye.com/blog/2384463