1.创建文件myrule
2.编写myrule内容
package com.myrule;
@Configuration
public class MySelfRule {
@Bean
public IRule myRule(){
return new RandomRule(); //随机的方法
}
}
3.在主启动类中加入这个注解
CLOUD-PAYMENT-SERVICE为服务名称
configuration为刚才我们写的类
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
4.在config中实现restTemplate
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
5.在控制层实现请求接口
@RestController
@CrossOrigin
@Slf4j
public class OrderController {
//public static final String PAYMENT_URL = "http://localhost:8001";
public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
@Resource
private RestTemplate restTemplate;
@GetMapping(value = "/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}
@GetMapping(value = "/consumer/payment/get")
public CommonResult<Payment> getById(@RequestParam("id") int id){
return restTemplate.getForObject(PAYMENT_URL + "/get?id=" + id, CommonResult.class);
}
}