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

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);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45432665/article/details/113892707
今日推荐