如果注册中心是eureka那么使用ribbon我们不需要额外添加pom配置信息,eurekaClient默认加载了ribbon的信息。
我们以restTemplate为例使用ribbon
yml配置:
#指定为某个服务配置负载规则
test1:
ribbon:
#配置自定义策略
NFLoadBalancerRuleClassName: com.example.springcloud.testdemo.ribbonConfig.MyRule
ribbon-java:
ribbon:
#配置随机策略
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
---
#为所有服务配置统一规则
ribbon:
#所有服务都使用随机策略
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
eureka中的服务信息:
java定义配置类:
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;
/**
* Created by py
* 2020/3/10
*/
@Configuration
public class RibbonComponent {
@Bean
@LoadBalanced //todo 通过该注解实现负载均衡
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
调用代码:
@RestController
public class RibbonTest1Controller {
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/ribbon/test1")
public String queryTestRestTemplate(){
/**此处我们写的是http://服务名/请求路径;ribbon会在我们的服务列表找到根据服务名找到对应的服务信息,然后将服务名“test1”替换成ip:port;然后在进行实际的求情。
转换后的请求 http://ip:port/eureka-clinet1/ribbonTest */
String url = "http://test1/eureka-clinet1/ribbonTest";
Map<String,String> map = new HashMap<String,String>(){{
put("name","ribboon-test");
}};
//springcloud中配套封装使用的http请求;不再需要我们手动创建http,关闭http
ResponseEntity<String> result =restTemplate.postForEntity(url,map,String.class);
System.err.println(result.getBody());
return result.getBody();
}
}
示意图: