使用Ribbon+restTemplate实现改变默认负载均衡

1.创建文件myrule
使用Ribbon+restTemplate实现改变默认负载均衡
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
使用Ribbon+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);
    }
}

上一篇:WTF Python课堂(一)


下一篇:SpringBoot集成Swagger3,还想来份离线文档?真酷炫