SpringCloud 系列文章

Easter79
• 阅读 551

SpringCloud

生产者与消费者

上一篇文章我们介绍了Euarka的搭建,本篇文章,我们搭建俩个服务,生产者服务与消费者服务。

我们就以电商系统为例:服务生产者,订单查询服务order-server,服务消费者order-client

说明:order-server 服务提供查询订单信息的功能
order-client作为消费者服务,查询订单信息。

生产者服务搭建

SpringCloud 系列文章


选择我们需要的依赖,具体依赖如下:

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

spring-cloud-starter-netflix-eureka-client 表示该服务是一个eureka的客户端,
订单服务会注册到eureka服务端上

依赖添加完成后,我们需要在SpringBoot项目的入口类上加上@EnableDiscoveryClient注解,
表示开启服务注册到eureka服务上:

@SpringBootApplication
@EnableDiscoveryClient
public class OrderServiceApplication {

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

}

接下来,需要我们对订单服务进行必要的配置:

server:
  port: 8081

spring:
  application:
    name: order-service

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka

说明:server.prot:订单服务的端口
spring.application.name:订单服务的名称,
这个名称会注册到eureka服务上
eureka.client.service-url.defaultZone:eureka服务的地址。

经过简单的配置以后,我们启动服务,访问eureka服务,http://localhost:8761,如下图:

SpringCloud 系列文章

我们将订单服务以及注册到eureka服务上了。此事,我们提供一个订单查询的接口,模拟订单查询功能。

@RestController
@RequestMapping("query")
public class OrderQueryController {
    @Autowired
    OrderQueryService queryService;

    @RequestMapping("info")
    public String queryOrder(){
        return queryService.queryOrder();
    }
}


@Service
public class OrderQueryService {

    public String queryOrder(){
        return "订单信息查询成功";
    }
}

消费者服务搭建

只需要像搭建服务提供者一样搭建服务消费者就可以,搭建完成以后,我们使用RestTemplate来调用订单服务进行订单信息查询,具体配置及代码如下:

server:
  port: 8082

spring:
  application:
    name: order-client

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka


//提供一个RestTemplate实例
@SpringBootApplication
@EnableDiscoveryClient
public class OrderClientApplication {

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

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

//编写测试接口
@RestController
public class ClientController {
    @Autowired
    ClientService clientService;

    @RequestMapping(value = "/info",method = RequestMethod.GET)
    public String queryOrderInfo(){
        return "restTemplate访问服务提供者返回的信息:"+clientService.queryOrderInfo();
    }
}

//模拟具体查询业务逻辑
@Service
public class ClientService {

    @Autowired
    RestTemplate restTemplate;

    public String queryOrderInfo(){
        System.out.println("通过restTemplate访问服务提供者");
        return restTemplate.getForEntity("http://ORDER-SERVER/query/info",               String.class).getBody();
    }

}

RestTemplate 介绍:
是spring框架提供的可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。

源码分析

部分源码如下,可以看出,它包含了Get、Post、Put等请求,比如Get请求包含俩种方法getForObjectgetForEntity,他们有什么区别呢?

  • 从接口的签名上,可以看出一个是直接返回预期的对象,一个则是将对象包装到 ResponseEntity 封装类中

  • 如果只关心返回结果,那么直接用 getForObject 即可

  • 如果除了返回的实体内容之外,还需要获取返回的header等信息,则可以使用 getForEntity

    @Override @Nullable public T getForObject(String url, Class responseType, Object... uriVariables) throws RestClientException { RequestCallback requestCallback = acceptHeaderRequestCallback(responseType); HttpMessageConverterExtractor responseExtractor = new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger); return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables); } @Override @Nullable public T getForObject(String url, Class responseType, Map<String, ?> uriVariables) throws RestClientException { RequestCallback requestCallback = acceptHeaderRequestCallback(responseType); HttpMessageConverterExtractor responseExtractor = new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger); return execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables); } @Override @Nullable public T getForObject(URI url, Class responseType) throws RestClientException { RequestCallback requestCallback = acceptHeaderRequestCallback(responseType); HttpMessageConverterExtractor responseExtractor = new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger); return execute(url, HttpMethod.GET, requestCallback, responseExtractor); } @Override public ResponseEntity getForEntity(String url, Class responseType, Object... uriVariables) throws RestClientException { RequestCallback requestCallback = acceptHeaderRequestCallback(responseType); ResponseExtractor<ResponseEntity> responseExtractor = responseEntityExtractor(responseType); return nonNull(execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables)); } @Override public ResponseEntity getForEntity(String url, Class responseType, Map<String, ?> uriVariables) throws RestClientException { RequestCallback requestCallback = acceptHeaderRequestCallback(responseType); ResponseExtractor<ResponseEntity> responseExtractor = responseEntityExtractor(responseType); return nonNull(execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables)); } @Override public ResponseEntity getForEntity(URI url, Class responseType) throws RestClientException { RequestCallback requestCallback = acceptHeaderRequestCallback(responseType); ResponseExtractor<ResponseEntity> responseExtractor = responseEntityExtractor(responseType); return nonNull(execute(url, HttpMethod.GET, requestCallback, responseExtractor)); } // HEAD @Override public HttpHeaders headForHeaders(String url, Object... uriVariables) throws RestClientException { return nonNull(execute(url, HttpMethod.HEAD, null, headersExtractor(), uriVariables)); } @Override public HttpHeaders headForHeaders(String url, Map<String, ?> uriVariables) throws RestClientException { return nonNull(execute(url, HttpMethod.HEAD, null, headersExtractor(), uriVariables)); } @Override public HttpHeaders headForHeaders(URI url) throws RestClientException { return nonNull(execute(url, HttpMethod.HEAD, null, headersExtractor())); } // POST @Override @Nullable public URI postForLocation(String url, @Nullable Object request, Object... uriVariables) throws RestClientException { RequestCallback requestCallback = httpEntityCallback(request); HttpHeaders headers = execute(url, HttpMethod.POST, requestCallback, headersExtractor(), uriVariables); return (headers != null ? headers.getLocation() : null); } @Override @Nullable public URI postForLocation(String url, @Nullable Object request, Map<String, ?> uriVariables) throws RestClientException { RequestCallback requestCallback = httpEntityCallback(request); HttpHeaders headers = execute(url, HttpMethod.POST, requestCallback, headersExtractor(), uriVariables); return (headers != null ? headers.getLocation() : null); } @Override @Nullable public URI postForLocation(URI url, @Nullable Object request) throws RestClientException { RequestCallback requestCallback = httpEntityCallback(request); HttpHeaders headers = execute(url, HttpMethod.POST, requestCallback, headersExtractor()); return (headers != null ? headers.getLocation() : null); } @Override @Nullable public T postForObject(String url, @Nullable Object request, Class responseType, Object... uriVariables) throws RestClientException { RequestCallback requestCallback = httpEntityCallback(request, responseType); HttpMessageConverterExtractor responseExtractor = new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger); return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables); } @Override @Nullable public T postForObject(String url, @Nullable Object request, Class responseType, Map<String, ?> uriVariables) throws RestClientException { RequestCallback requestCallback = httpEntityCallback(request, responseType); HttpMessageConverterExtractor responseExtractor = new HttpMessageConverterExtractor<>(responseType, getMessageConverters(), logger); return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables); } @Override @Nullable public T postForObject(URI url, @Nullable Object request, Class responseType) throws RestClientException { RequestCallback requestCallback = httpEntityCallback(request, responseType); HttpMessageConverterExtractor responseExtractor = new HttpMessageConverterExtractor<>(responseType, getMessageConverters()); return execute(url, HttpMethod.POST, requestCallback, responseExtractor); } @Override public ResponseEntity postForEntity(String url, @Nullable Object request, Class responseType, Object... uriVariables) throws RestClientException { RequestCallback requestCallback = httpEntityCallback(request, responseType); ResponseExtractor<ResponseEntity> responseExtractor = responseEntityExtractor(responseType); return nonNull(execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables)); } @Override public ResponseEntity postForEntity(String url, @Nullable Object request, Class responseType, Map<String, ?> uriVariables) throws RestClientException { RequestCallback requestCallback = httpEntityCallback(request, responseType); ResponseExtractor<ResponseEntity> responseExtractor = responseEntityExtractor(responseType); return nonNull(execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables)); } @Override public ResponseEntity postForEntity(URI url, @Nullable Object request, Class responseType) throws RestClientException { RequestCallback requestCallback = httpEntityCallback(request, responseType); ResponseExtractor<ResponseEntity> responseExtractor = responseEntityExtractor(responseType); return nonNull(execute(url, HttpMethod.POST, requestCallback, responseExtractor)); }

接下来,我们启动,服务消费者,此时访问我们的eureka服务,已经有俩个服务注册上来了,如下:

SpringCloud 系列文章

最后我们来验证一下,服务消费者是否能调用到服务提供者,在浏览器输出http://localhost:8082/info

SpringCloud 系列文章

根据返回的信息,确认服务调用成功。

总结:以上就是我们基于eureka的服务注册发现机制,实现的服务之间的相互调用。当然,这里边还有很多的细节需要讨论,后续的文章,继续和大家讨论。

如有收获请关注微信公众号!!!

SpringCloud 系列文章

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
3个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Stella981 Stella981
3年前
Docker 部署SpringBoot项目不香吗?
  公众号改版后文章乱序推荐,希望你可以点击上方“Java进阶架构师”,点击右上角,将我们设为★“星标”!这样才不会错过每日进阶架构文章呀。  !(http://dingyue.ws.126.net/2020/0920/b00fbfc7j00qgy5xy002kd200qo00hsg00it00cj.jpg)  2
Stella981 Stella981
3年前
Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法
Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法参考文章:(1)Google地球出现“无法连接到登录服务器(错误代码:c00a0194)”解决方法(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.codeprj.com%2Fblo
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
9个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k