Microservice Components: Load Balancing Ribbon
1. Introduction of Ribbon
In microservices, usually an application system needs to deploy multiple instances, which are distributed in different running containers. In order to avoid all requests being concentrated on one machine, so that requests are evenly distributed on multiple instance application systems, the load balancing component Ribbon is needed at this time.
2. Ribbon use
2-1 Start the eureka registry
@SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } }
Start 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/
Start 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 Start the service provider
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 View service registration status
http://mengka-host.local:8762/
2-4 Start the service call client
/** * Instantiate RestTemplate and enable load balancing capability through @LoadBalanced annotation. * @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 of the service provider 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 Call the findById interface service
http://127.0.0.1:8010/ribbon/1
Service calls are evenly distributed across 2 service provider machines:
3. Feign use
Feign is a declarative, templated HTTP client. Spring cloud adds annotation support to Feign, and integrates Ribbon and Eureka to provide load balancing, making it easier to write service invocation clients.
3-1 Start the service call client
使用@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台服务提供者机器上: