第四篇:搭建服务消费者

应用间通讯协议

所谓服务消费者,就是它需要调用的服务不在本地,需要远程调用,而远程调用目前主流的协议就是HTTP和RPC.

dubbo远程通讯协议:RPC

springcloud远程通讯协议:HTTP  (HTTP RESTful)

Service Conumer服务消费者

1:新建springcloud-service-conumer模块

2:继承父工程

3:修改application.properties配置文件

1

2

3

4

5

6

7

8

#允许注册eureka注册中心,默认值就是true

eureka.client.register-with-eureka=true

#允许从eureka注册中心找服务,并调用,默认值就是true

eureka.client.fetch-registry=true

#eureka的server地址,如果eureka服务多个用逗号隔开

eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

#应用名

spring.application.name=spring-cloud-service-consumer

4:主程序加上@EnableEurekaClient注解

1

2

3

4

5

6

7

8

9

10

11

12

13

14

package com.wendao.provider.consumer;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

 

@SpringBootApplication

@EnableEurekaClient

public class ConsumerApplication {

    public static void main(String[] args) {

        SpringApplication.run(ConsumerApplication.class, args);

    }

 

}

5:启动该工程,访问http://localhost:8761/(注册中心ui界面地址)看到如下界面

2018-02-13_162251.png

 

6:使用resttemplate调用远程服务,而resttemplate的使用又有三种方式

方式一:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

package com.wendao.provider.consumer.web;

import com.wendao.provider.consumer.pojo.User;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.client.RestTemplate;

 

@RestController

public class ConsumerController {

 

 

    private RestTemplate restTemplate = new RestTemplate();

 

    @RequestMapping("/findOne")

    public User findOne(){

        User user = restTemplate.getForObject("http://localhost:8181/user/1", User.class);

        return user;

    }

 

}

RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求,可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。

 

第一种方式小结:第一种方式简单粗暴,但是这种方式有弊端,最直接的弊端是,如果服务提供者是一个集群,我们永远只能调用集群中的某一个。没法实现负载均衡。

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值