SpringCloud极简入门 | 第二讲: 服务消费者通过注册中心调用生产者(方式一:RestTemplate、Ribbon)(F版本)

开篇点题:

上篇讲到小商家(生产者)注册到某宝或者某东上(注册中心),那作为消费者的我们如何调用的呢?

很简单下载个app登陆账号,然后选购商品之后付款等待快递就ok了....

可是..可是,打断以下,那我程序怎么调用生产者的接口呢?

方案一:RestTemplate+Ribbon

方案二:Feign的方式,对就是这个spring-cloud-starter-openfeign

对于这两种方式有疑惑的可以在下面留言,有问必有答。编程之路期待你的参与

Tip:ribbon是一个负载均衡客户端,可以很好的控制htt和tcp的一些行为。Feign默认集成了ribbon。

Demo开始

案例还是采用springcloud-01-eureka-producer-consumer模块为例

主题:创建消费者模块,然后RestTemplate+Ribbon方式调用注册中心的生产者 IP/hello/name

1.启动注册中心 2.启动生产者

(注意启动顺序,此外代码已经详细解析参考   SpringCloud极简入门 |第一讲)

3.创建消费者

pom文件引入:(注意源代码种用到是spring-cloud-starter-openfeign)

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>
    </dependencies>

启动类


@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudConsumerApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringCloudConsumerApplication.class, args);
		System.out.println("/*************spring cloud consumer 9001********************/");
	}

	/**
	 * ioc注入一个bean: restTemplate;
	 * 并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能
	 * @return
	 */
	@Bean
	@LoadBalanced
	RestTemplate restTemplate() {
		return new RestTemplate();
	}
}

写个Service:注意spring-cloud-provider是生产者的application.name的值(就是上篇说很重要的那个配置)

@Service
public class HelloServiceRibbon {

    @Autowired
    RestTemplate restTemplate;

    public String hello( String name){
        return restTemplate.getForObject("http://spring-cloud-provider/hello?name="+name,String.class);
    };
}

Controller调用走起


@RestController
public class ConsumerController {
 
    @Autowired
    HelloServiceRibbon helloServiceRibbon;

    @RequestMapping(value = "/hello1/{name}")
    public String helloribbon(@PathVariable("name") String name){
        System.out.println("/***********consumer-helloServiceRibbon*****/");
        return  helloServiceRibbon.hello(name);
    }

}

写完了,开始测试了,启动消费者端口9001

配置文件:

spring.application.name=spring-cloud-consumer
server.port=9001
eureka.client.serviceUrl.defaultZone=http://localhost:7001/eureka/

测试开始(成功)

不要问是hello1为什么不是hello,因为那个controller被Feign方式调用占用了,不好意思

End:

上面代码只是一个基本入门,希望有所收获

其实负载包含多种策略,还支持自定义负载,基本入门完成后就开始高级架构篇欢迎转发关注

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

十年呵护

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

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

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

打赏作者

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

抵扣说明:

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

余额充值