springcloud应用之ribbon

springcloud应用之ribbon

阅读提示

请先阅读eureka

ribbon是什么

ribbon是netflix提供的一个用来解决客户端负载均衡的组件

ribbon的使用

@Configuration
public class AppConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
	//可不写rule,有默认的,应该是轮询
    @Bean
    public IRule myRule(){
        return new RetryRule();
    }
}

调用方式

@RestController
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("queryOrder")
    public String queryOrder(){
        ResponseEntity<String> response = restTemplate.getForEntity("http://order/order",String.class);
        return response.getBody();
    }
}

调用不同的微服务使用不同的算法

如果user模块想使用A负载均衡算法调用order,使用B算法调用money,可以使用如下办法:
先写两个配置文件

@Configuration
public class MoneyRuleConfig {
    @Bean
    public IRule rule(){
        return new RoundRobinRule();
    }
}

@Configuration
public class OrderRuleConfig {
    @Bean
    public IRule rule(){
        return new RandomRule();
    }
}

但是注意这两个config必须在启动类UserApplication所在包的外面,也就是compontScan包外面如图
在这里插入图片描述
可以看到config包和compontScan的 com.lry.eureka.user是平级关系
启动类加上

@RibbonClients({
        @RibbonClient(name = "money",configuration = MoneyRuleConfig.class),
        @RibbonClient(name = "order",configuration = OrderRuleConfig.class),
})

负载均衡算法

请见笔者另一篇博客
负载均衡

发布了164 篇原创文章 · 获赞 81 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/LiuRenyou/article/details/104770467