400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

微服务(三)——远程调用-创新互联

目录

创新互联建站专注为客户提供全方位的互联网综合服务,包含不限于网站设计、成都做网站、开化网络推广、小程序开发、开化网络营销、开化企业策划、开化品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们大的嘉奖;创新互联建站为所有大学生创业者提供开化建站搭建服务,24小时服务热线:028-86922220,官方网址:www.cdcxhl.com
前言

微服务都是独立部署的,要实现一个业务可能需要多个服务之间的通信,所以远程调用必不可少,本文将提供三种远程调用的方案:jodd-http、RestTemplate、Feign。

在此说一下 springboot父子 工程的搭建流程:

注意:


1. RestTemplate

前期准备:

1. 导入依赖

RestTemplate 是spring自带的远程调用工具,所以只要有spring的依赖,都可以直接使用(随便导入一个spring-boot-dependencies或者spring-boot-starter-web都行)。

2. 代码

在使用RestTemplate之前,需要先在容器中注册。将下述代码写在一个配置类(@Configuration)中,或者直接写在 启动类(main)中都可以。

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

controller代码:

@RequestMapping("/rest")
@org.springframework.web.bind.annotation.RestController
public class RestController {private static final String NAME = "rest_template";

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping
    public String sayHello() {String url = "http://127.0.0.1:8088/remote/" + NAME;
        String msg = restTemplate.getForObject(url, String.class);
        return msg;
    }
}

测试: 请求成功。

3. 常用方法

RestTemplate的使用比较简单,这里再简单说一下它的常用方法:

方法请求说明
getForEntityGET常用:publicResponseEntitygetForEntity(地址, 返回类型)
getForObjectGET常用:publicT getForObject(地址, 返回类型)
对getForEntity函数的进一步封装,只关注返回的消息体的内容,对其他信息都不关注
postForEntityPOST常用:publicResponseEntitypostForEntity(地址, 上传的参数(可为空),返回类型)
postForObjectPOST常用:publicResponseEntitypostForObject(地址, 上传的参数(可为空),返回类型)
对postForEntity函数的进一步封装,只关注返回的消息体的内容,对其他信息都不关注
postForLocationPOST常用:public URI postForLocation(地址, 上传的参数(可为空))
返回新资源所在的 url
putPUT常用:public void put(地址, 上传的参数(可为空))
deleteDELETE常用:public void delete(地址, 上传的参数)

在这里补充一下RestfulHTTP动词

2. jodd-http 1. 引入依赖

需要导入两个依赖:

com.alibabafastjson1.2.83org.joddjodd-http3.7.1
2. 代码

工具类:

import com.alibaba.fastjson.JSONObject;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;

import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpUtil {public static String post(String url, Mapmap) {HttpResponse res = HttpRequest.post(url).connectionTimeout(90000).timeout(90000)
                .contentType("application/json", "UTF-8")
                .bodyText(JSONObject.toJSONString(map), "application/json", "UTF-8")
                .send();
        res.charset("utf-8");
        return res.bodyText();
    }

    public static String post(String url, String jsonStr) {HttpResponse resp = HttpRequest.post(url).connectionTimeout(60000).timeout(60000)
                .contentType("application/json", StandardCharsets.UTF_8.toString())
                .bodyText(jsonStr ,"application/json", "UTF-8")
                .send();
        resp.charset(StandardCharsets.UTF_8.toString());
        return resp.bodyText();
    }

    public static String get(String url, Mapparams) {HttpRequest request = HttpRequest.get(url);
        if (params != null) {request.query(params);
        }
        HttpResponse response = request.send();
        return response.bodyText();
    }
}

Controller:

@RequestMapping("/jodd")
@RestController
public class JoddController {private static final String NAME = "jodd_http";

    @GetMapping
    public String sayHello() {String url = "http://127.0.0.1:8088/remote/" + NAME;
        String msg = HttpUtil.get(url, new HashMap<>());
        return msg;
    }
}
3. 测试

注意: 这个我在之前的文章中讲过,点击跳转 ,这里就不再多说。

3. Feign

Feign是一个声明式的http客户端:点击图片跳转。

鉴于前面的两种方法,对于参数复杂URL难以维护,所以建议使用Feign

1. 引入依赖

Feign是基于springcloud来发起远程请求的,需要与nacos等注册中心搭配使用,点击跳转注册中心文章。

要引入Feign依赖,就需要先引入springcloud的依赖:

org.springframework.cloudspring-cloud-dependencies2021.0.5pomimport

注意: 引入springcloud依赖的时候,需要注意springboot的版本。

  • springboot 与 springcloud 的版本对应关系
    点击图片跳转

然后导入Feign依赖:

org.springframework.cloudspring-cloud-starter-openfeign3.1.2

注意: 启动项目报错:No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalancer?

解决方案: https://blog.csdn.net/qq_43788878/article/details/115764008

2. 使用过程
  1. 在启动类上添加一个@EnableFeignClients

  2. 编写Feign接口

    @Component
    //@FeignClient:微服务客户端注解,value:指定微服务的名字,这样就可以使Feign客户端直接找到对应的微服务
    @FeignClient(value = "remote")
    public interface MyFeignClient {@GetMapping("/remote/{name}")
        String sayHello(@PathVariable("name") String name);
    }
    

    这个客户端主要是基于SpringMVC的注解来声明远程调用的信息,比如:

    • 服务名称:remote
    • 请求方式:GET
    • 请求路径:/remote/{name}
    • 请求参数:String name
    • 返回值类型:String

    这样,Feign就可以帮助我们发送http请求,无需自己使用RestTemplate来发送了。

  3. controller

    @RestController("/feign")
    public class FeignController {private static final String NAME = "feign";
    
        @Resource
        private MyFeignClient feignClient;
    
        @GetMapping
        public String sayHello() {String msg = feignClient.sayHello(NAME);
            return msg;
        }
    }

以上就是Feign的使用步骤,因为懒得去搭建注册中心,所以就不测试了。

3. 自定义配置

Feign可以支持很多的自定义配置,如下表所示:

类型作用说明
feign.Logger.Level修改日志级别包含四种不同的级别:NONE、BASIC、HEADERS、FULL
feign.codec.Decoder响应结果的解析器http远程调用的结果做解析,例如解析json字符串为java对象
feign.codec.Encoder请求参数编码将请求参数编码,便于通过http请求发送
feign. Contract支持的注解格式默认是SpringMVC的注解
feign. Retryer失败重试机制请求失败的重试机制,默认是没有,不过会使用Ribbon的重试

一般情况,直接使用默认配置就OK了。

自定义配置的方法:

4. 优化

优化演示:

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


本文题目:微服务(三)——远程调用-创新互联
本文URL:http://mzwzsj.com/article/degijs.html

其他资讯

让你的专属顾问为你服务