05-LoadBalancer负载均衡 (2)

上面代码中,@LoadBalanced 注解开启了RestTemplate的负载均衡,具体原理后面深入源码学习时再做了解。这里只需要了解该注解标记后,该http请求会有负载均衡效果。

ConsumerController

服务调用,

import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; /** * Created by huangmin */ @RestController public class ConsumerController { private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerController.class); @Autowired private RestTemplate restTemplate; // HTTP客户端 @RequestMapping("/hello") public String hello() { String providerMsg = restTemplate.getForEntity("http://PROVIDER-SERVICE/hello", String.class).getBody(); return "Hello,I'm Customer! msg from provider : <br/><br/> " + providerMsg; } } 3、Ribbon

如果需要使用Ribbon的话,我们只需要改一下依赖文件即可:

<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <exclusions> <exclusion> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-loadbalancer</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> <version>2.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>

这里移出了loadbalancer ,添加Ribbon的包。其他配置不用动即可换成Ribbon

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzwsps.html