您的位置:首页 > 编程语言 > Java开发

springcloud ribbon搭建服务负载均衡

2018-03-27 13:50 991 查看
加入ribbon依赖:<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>在启动器中加入:@SpringBootApplication
@EnableEurekaClient
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}

@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
RestTemplate
中我们增加了一个
@LoadBalanced
注解,该注解就是能够让
RestTemplate
启用客户端负载均衡。
启动eureka服务器,启动多个service
访问资源,输出端口号,会发现端口号交替出现,则测试成功

 直接使用Ribbon的API

另外,除了使用
@LoadBalanced
注解外,我们还可以直接使用Ribbon所提供的
LoadBalancerClient
来实现负载均衡:
@RestController
public class HelloController {
protected Logger logger = LoggerFactory.getLogger(HelloController.class);

@Autowired
private RestTemplate restTemplate;

@Autowired
private LoadBalancerClient loadBalancerClient;

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
return restTemplate.getForEntity("http://SERVICE-HELLO/hello", String.class).getBody();
}

@RequestMapping(value = "/helloEx", method = RequestMethod.GET)
public String helloEx() {
ServiceInstance instance = this.loadBalancerClient.choose("SERVICE-HELLO");
URI helloUri = URI.create(String.format("http://%s:%s/hello", instance.getHost(), instance.getPort()));
logger.info("Target service uri =
4000
{}. ", helloUri.toString());
return new RestTemplate().getForEntity(helloUri, String.class).getBody();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: