1、作用:负载均衡+RestTemplate调用
1⃣️Module:cloud-consumer-order80
2⃣️POM:spring-cloud-starter-netflix-eureka-client 引入了Ribbon,不需要单独引用。
3⃣️yml:不需要更改
4⃣️主启动:不需要更改
5⃣️Config:调用者模块中配置类中配置RestTemplate
@Configuration
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
6⃣️Controller:
RestTemplate的使用
- getForObject / getForEntity
- postForObject / postForEntity
@RestController
@Slf4j
public class OrderController {
public static final String PAYMENT_URL = "http://localhost:8001";
@Resource
private RestTemplate restTemplate;
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPaymentById2(@PathVariable("id") Long id) {
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()) {
log.info(entity.getStatusCode()+"");
return entity.getBody();
} else {
return new CommonResult<>(444, "操作失败");
}
}
}
2、Ribbon核心组件IRule
2.2 如何替换
1⃣️新建com.atguigu.myrule.MySelfRule
@Configuration
public class MySelfRule {
@Bean
public IRule myRule(){
return new RandomRule();
}
}
2⃣️主启动类添加@RibbonClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MySelfRule.class)
表示对于CLOUD-PAYMENT-SERVICE服务,使用MySelfRule中配置的规则。