栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

详解Spring cloud使用Ribbon进行Restful请求

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

详解Spring cloud使用Ribbon进行Restful请求

写在前面

本文由markdown格式写成,为本人第一次这么写,排版可能会有点乱,还望各位海涵。
 主要写的是使用Ribbon进行Restful请求,测试各个方法的使用,代码冗余较高,比较适合初学者,介意轻喷谢谢。

前提

  1. 一个可用的Eureka注册中心(文中以之前博客中双节点注册中心,不重要)
  2. 一个连接到这个注册中心的服务提供者
  3. 一个ribbon的消费者

注意:文中使用@GetMapping、@PostMapping、@PutMapping、@DeleteMapping等注解需要升级 spring-boot-starter-parent版本到1.5.9.REALEASE以上(1.3.7.RELEASE版本没有这些注解)

建议:每个微服务应用都有自己的spring-boot-maven-plugin和maven-compiler-plugin并指定jdk编译版本为1.8 ,指定方式如下,pom.xml中添加

  
    
      
 org.springframework.boot
 spring-boot-maven-plugin
      
      
 org.apache.maven.plugins
 maven-compiler-plugin
 
   1.8
   1.8
 
      
    
  

测试项目构建

Eureka注册中心:参考注册中心的搭建 
 服务提供者:参考注册服务提供者
ribbon消费者:参考服务发现与消费

项目搭建完后,记得按照这几个教程中提到的配置hosts文件

为了防止项目中的RequestMapping相同,这里就删除所有的controller类(服务提供者和消费者),接下来我会将每个restful方法都封装成一个类,方便大家查看

Get请求

getForEntity:此方法有三种重载形式,分别为:

  1. getForEntity(String url, Class responseType)
  2. getForEntity(String url, Class responseType, Object... uriVariables)
  3. getForEntity(String url, Class responseType, Map uriVariables)
  4. getForEntity(URI url, Class responseType)

注意:此方法返回的是一个包装对象ResponseEntity其中T为responseType传入类型,想拿到返回类型需要使用这个包装类对象的getBody()方法

getForObject:此方法也有三种重载形式,这点与getForEntity方法相同:

  1. getForObject(String url, Class responseType)
  2. getForObject(String url, Class responseType, Object... uriVariables)
  3. getForObject(String url, Class responseType, Map uriVariables)
  4. getForObject(URI url, Class responseType)

注意:此方法返回的对象类型为responseType传入类型

为了方便测试,这里分别在服务提供者和服务消费者中提供相同的User类,用于方便测试

package com.cnblogs.hellxz;


public class User {

  private String name;
  private String sex;
  private String phone;
  public User(){}
  public User(String name, String sex, String phone) {
    this.name = name;
    this.sex = sex;
    this.phone = phone;
  }

  public String toString(){
    return "user:{"
 +"name: " + name + ", "
 +"sex: " + sex + ", "
 +"phone: " + phone
 +" }";
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getSex() {
    return sex;
  }

  public void setSex(String sex) {
    this.sex = sex;
  }

  public String getPhone() {
    return phone;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }
}

下边我们在服务提供者处创建一个GetRequestController

package com.cnblogs.hellxz;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;


@RestController
public class GetRequestController {

  @Autowired
  private DiscoveryClient client; //注入发现客户端

  private final Logger logger = Logger.getLogger(GetRequestController.class);

  
  @GetMapping(value = "/hello")
  public String hello(){
    //获取服务实例,作用为之后console显示效果
    ServiceInstance serviceInstance = client.getLocalServiceInstance();
    logger.info("/hello host:"+serviceInstance.getHost()+" service_id:" +serviceInstance.getServiceId());
    return "hello";
  }

  
  @GetMapping(value = "/greet/{dd}")
  public String greet(@PathVariable String dd){
    ServiceInstance serviceInstance = client.getLocalServiceInstance();
    logger.info("/hello host:"+serviceInstance.getHost()+" service_id:" +serviceInstance.getServiceId());
    return "hello "+dd;
  }

  
  @GetMapping("/user")
  public User getUser(){
    ServiceInstance serviceInstance = client.getLocalServiceInstance();
    logger.info("/user "+serviceInstance.getHost()+" port:"+serviceInstance.getPort()+" serviceInstanceid:"+serviceInstance.getServiceId());
    return new User("hellxz","male", "123456789");
  }

  
  @GetMapping("/user/{name}")
  public User getUserSelect(@PathVariable String name){
    ServiceInstance serviceInstance = client.getLocalServiceInstance();
    logger.info("/user "+serviceInstance.getHost()+" port:"+serviceInstance.getPort()+" serviceInstanceid:"+serviceInstance.getServiceId());
    if(name.isEmpty()){
      return new User();
    }else if(name.equals("hellxz")){
      return new User("hellxz","male", "123456789");
    }else{
      return new User("随机用户","male", "987654321");
    }
  }
}

接下来我们在服务消费者项目中创建GetRequestController

package com.cnblogs.hellxz;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;


@RestController
public class GetRequestController {

  private Logger logger = Logger.getLogger(GetRequestController.class);

  @Autowired
  //注入restTemplate
  private RestTemplate restTemplate;

  
  @GetMapping(value="/entity/noparam")
  public String noParamGetForEntity(){
    //这里注释掉,因为之前想当然使用了直链访问服务提供者的接口,这样是不会返回结果的,而且会报错
    //return restTemplate.getForEntity("http://localhost:8080/hello",String.class).getBody();
    //使用restTemplate调用微服务接口
    return restTemplate.getForEntity("http://hello-service/hello", String.class).getBody();

  }

  
  @GetMapping("/entity/type")
  public User getForEntityIdentifyByType(){
    //不传参返回指定类型结果
    ResponseEntity entity = restTemplate.getForEntity("http://hello-service/user", User.class);
    User body = entity.getBody();
    logger.info("user:"+body);
    return body;
    //以上可简写为
//    return restTemplate.getForEntity("http://hello-service/user", User.class).getBody();
  }

  
  @GetMapping(value="/entity")
  //如果接收的参数是使用参数没有使用?有则使用@PathVariable,否则用@RequestParam
  public String getForEntityByQuestionMarkParam(@RequestParam("name") String name){
    //主要测试getEntity方法,这里测试直接传参
    return restTemplate.getForEntity("http://hello-service/greet/{1}", String.class, name).getBody();
  }

  
  @GetMapping(value="/entity/map/{name}")
  //如果接收的参数是使用参数没有使用?有则使用@PathVariable,否则用@RequestParam
  public String getForEntityByMap(@PathVariable("name") String name){
    //主要测试getEntity方法,这里测试map传参
    Map reqMap = new HashMap();
    reqMap.put("name",name);
    return restTemplate.getForEntity("http://hello-service/greet/{name}", String.class,reqMap).getBody();
  }

  
  @GetMapping("/entity/uri")
  public String getForEntityByURI(){
    //使用uri进行传参并访问
    UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://hello-service/greet/{name}").build().expand("laozhang").encode();
    URI uri = uriComponents.toUri();
    return restTemplate.getForEntity(uri, String.class).getBody();

  }
  
  @GetMapping("/object")
  public User getForObjectWithNoParam(){
    //相比getForEntity方法,获取对象可以省去调用getBody
    return restTemplate.getForObject("http://hello-service/user", User.class);
  }

  
  @GetMapping("/object/map")
  public User getForObjectByMap(){
    //使用map传参
    Map paramMap = new HashMap<>();
    paramMap.put("name","hellxz");
    return restTemplate.getForObject("http://hello-service/user", User.class, paramMap);
  }

  
  @GetMapping("/object/param/{name}")
  public User getForObjectByParam(@PathVariable String name){
    return restTemplate.getForObject("http://hello-service/user/{name}",User.class, name);
  }

  
  @GetMapping("/object/uri/{name}")
  public User getForObjectByURI(@PathVariable String name){
    UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://hello-service/user/{name}")
     .build().expand(name).encode();
    URI uri = uriComponents.toUri();
    return restTemplate.getForObject(uri,User.class);
  }
}

先启动注册中心,然后通过访问消费者对外提供的接口进行测试,这些都是本人实际操作过的了,这里就不写测试了

Post请求

post请求和get请求都有*ForEntity和*ForObject方法,其中参数列表有些不同,除了这两个方法外,还有一个postForLocation方法,其中postForLocation以post请求提交资源,并返回新资源的URI

postForEntity:此方法有三种重载形式,分别为:

  1. postForEntity(String url, Object request, Class responseType, Object... uriVariables)
  2. postForEntity(String url, Object request, Class responseType, Map uriVariables)
  3. postForEntity(URI url, Object request, Class responseType)

注意:此方法返回的是一个包装对象ResponseEntity其中T为responseType传入类型,想拿到返回类型需要使用这个包装类对象的getBody()方法

postForObject:此方法也有三种重载形式,这点与postForEntity方法相同:

  1. postForObject(String url, Object request, Class responseType, Object... uriVariables)
  2. postForObject(String url, Object request, Class responseType, Map uriVariables)
  3. postForObject(URI url, Object request, Class responseType)

注意:此方法返回的对象类型为responseType传入类型

postForLocation:此方法中同样有三种重载形式,分别为:

  1. postForLocation(String url, Object request, Object... uriVariables)
  2. postForLocation(String url, Object request, Map uriVariables)
  3. postForLocation(URI url, Object request)

注意:此方法返回的是新资源的URI,相比getForEntity、getForObject、postForEntity、postForObject方法不同的是这个方法中无需指定返回类型,因为返回类型就是URI,通过Object... uriVariables、Map uriVariables进行传参依旧需要占位符,参看postForEntity部分代码

按照之前的方式,我们分别在提供服务者和消费者的项目中分别创建PostRequestController

如下服务者PostRequestController代码如下:

package com.shunneng.springcloudhelloworld;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;

@RestController
public class PostRequestController {
  private Logger logger = Logger.getLogger(PostRequestController.class);

  
  @PostMapping("/user")
  public User returnUserByPost(@RequestBody User user){
    logger.info("/use接口 "+user);
    if(user == null) return new User("这是一个空对象","","");
    return user;
  }

  
  @PostMapping("/user/{str}")
  public User returnUserByPost(@PathVariable String str, @RequestBody User user){
    logger.info("/user/someparam 接口传参 name:"+str +" "+user);
    if(user == null) return new User("这是一个空对象","","");
    return user;
  }

  
  @PostMapping("/location")
  public URI returnURI(@RequestBody User user){
    //这里模拟一个url,真实资源位置不一定是这里
    UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://hello-service/location")
      .build().expand(user).encode();
    URI toUri = uriComponents.toUri();
    //这里不知道是什么问题,明明生成uri了,返回之后好像并没有被获取到
    logger.info("/location uri:"+toUri);
    return toUri;
  }
}

消费端PostRequestController代码:

package com.cnblogs.hellxz;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;

@RestController
public class PostRequestController {
  private Logger logger = Logger.getLogger(PostRequestController.class);
  @Autowired
  private RestTemplate restTemplate;

  
  @PostMapping("/entity")
  public User postForEntity(){
    User user = new User("hellxz1","1","678912345");
    ResponseEntity entity = restTemplate.postForEntity("http://hello-service/user/{str}", user, User.class, "测试参数");
    User body = entity.getBody(); //所有restTemplate.*ForEntity方法都是包装类,body为返回类型对象
    return body;
  }

  
  @PostMapping("/entity/uri")
  public User postForEntityByURI(){
    User user = new User("老张","1","678912345");
    //这里只是将url转成URI,并没有添加参数
    UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://hello-service/user")
     .build().encode();
    URI toUri = uriComponents.toUri();
    //使用user传参
    User object = restTemplate.postForObject(toUri, user, User.class);
    return object;
  }

  
  @PostMapping("/object")
  public User postForObject(){
    User user = new User("hellxz2","1","123654987");
    //这里url传1是为了调用服务者项目中的一个接口
    User responseBody = restTemplate.postForObject("http://hello-service/user/1", user, User.class);
    return responseBody;
  }

  
  @PostMapping("/location")
  public URI postForLocation(){
    User user = new User("hellxz3","1","987654321");
    URI uri = restTemplate.postForLocation("http://hello-service/location", user);
    //不知道为什么返回来是空,这个方法仅供参考吧,如果知道是什么情况,我会回来改的
    logger.info("/location uri:"+uri);
    return uri;
  }
}

Put请求&&Delete请求

put请求相对于get和post请求方法来的更为简单,其中无需指定put请求的返回类型,当然也没有返回值,也是三种重载,和之前写的基本一致,这里就不想多说了,delete请求和put请求都是没有返回值的,这里再特地重复写也没什么意思,这里先分别列出这两个请求的方法,代码写在一个类中了

put请求方法如下:

  1. put(String url, Object request, Object... uriVariables)
  2. put(String url, Object request, Map uriVariables)
  3. put(URI url, Object request)

delete请求方法如下:

  1. delete(String url, Object... uriVariables)
  2. delete(String url, Map uriVariables)
  3. delete(URI url)

在提供服务者项目中添加PutAndDeleteRequestController,代码如下

package com.cnblogs.hellxz;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;



@RestController
public class PutAndDeleteRequestController {

  private Logger logger = Logger.getLogger(PutAndDeleteRequestController.class);

  @PutMapping("/put")
  public void put(@RequestBody User user){
    logger.info("/put "+user);
  }

  @DeleteMapping("/delete/{id}")
  public void delete(@PathVariable Long id){
    logger.info("/delete id:"+id);
  }
}

在提供服务者项目中添加PutAndDeleteRequestController,代码如下

package com.cnblogs.hellxz;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RestController
public class PutRequestController {

  private Logger logger = Logger.getLogger(PostRequestController.class);
  @Autowired
  private RestTemplate restTemplate;

  
  @PutMapping("/put")
  public void put(@RequestBody User user){
    restTemplate.put("http://hello-service/put",user);
  }

  
  @DeleteMapping("/del/{id}")
  public void delete(@PathVariable Long id){
    restTemplate.delete("http://hello-service/delete/{1}", id);
  }
}

结语

这篇博文使用markdown写成,第一次写不知道如何将代码块中加入序号以及折叠代码功能,这可能不是一篇好文章,但是写这篇博文写了快两天,有什么好的建议欢迎评论交流,

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/141139.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号