Spring Cloud基础教程(三):服务消费者(Ribbon)

在上一篇的文章中,讲解了服务生产者的创建,创建了Service-Producer的两个实例。SpringCloud的服务调用有两种方式,Ribbon和Feign,本篇博客讲解下Ribbon的使用。

Ribbon实现了一套客户端的负载均衡工具,它是基于HTTP和TCP实现的。

一、准备

使用上一篇博客服务生产者的创建中创建的Eureka-Server和Service-Producer。

二、创建Consumer-Ribbon

gradle依赖为

dependencies {
	compile('org.springframework.boot:spring-boot-starter-web')
	compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-eureka', version: '1.4.4.RELEASE'
	compile('org.springframework.cloud:spring-cloud-starter-ribbon:1.4.4.RELEASE')
	testCompile('org.springframework.boot:spring-boot-starter-test')
}

添加@EnableDiscoveryClient注解,同时配置RestTemplate类的注入,添加 @LoadBalanced注解,进行负载均衡。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerRibbonApplication
{

	public static void main(String[] args) {
		SpringApplication.run(ConsumerRibbonApplication.class, args);
	}

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

添加测试Controller,对于RestTemplate的使用,我们的第一个url参数有一些特别。这里请求的host位置并没有使用一个具体的IP地址和端口的形式,而是采用了服务名的方式组成。那么这样的请求为什么可以调用成功呢?因为Spring Cloud Ribbon有一个拦截器,它能够在这里进行实际调用的时候,自动的去选取服务实例,并将实际要请求的IP地址和端口替换这里的服务名,从而完成服务接口的调用。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by wzj on 2018/5/19.
 */
@RestController
public class ConsumerController
{
    /**
     * 注入
     */
    @Autowired
    private RestTemplate restTemplate;


    @RequestMapping("/consumer")
    public String client()
    {
        return restTemplate.getForObject("http://service-producer/client",String.class);
    }
}

三、测试

同时启动Service-Producer-A、Service-Producer-B和Consumer-Ribbon


浏览器访问http://127.0.0.1:10006/consumer,结果负载到了Service-Producer-A


关闭Service-Producer-A服务,再次访问http://127.0.0.1:10006/consumer,发现负载到了Service-Producer-B


源码Github地址:https://github.com/HelloKittyNII/SpringCloud/tree/master/SpringCloudFramework

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dmfrm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值