废弃
见:ums(ribbon+RestTemplate负载均衡)访问notice集群
介绍
ribbon需要 服务治理和发现,如eureka
ribbon搭配RestTemplate,实现客户端负载均衡
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
注意
如果使用 eureka 2.x,默认依赖ribbon,所以不需要添加上面依赖
配置类
需要用到@LoadBalanced注解
package top.malaoshi.ums.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
使用
url设置成服务名
注意:是eureka server上显示的服务名
public static final String NOTICE_URL="http://NOTICE-SERVICE";
@Resource
private RestTemplate restTemplate;
@PostMapping(value="/follow")
public CommonResult follow(Notice notice){
return restTemplate.postForObject(NOTICE_URL+"/sendNotice/",notice, CommonResult.class);
}


