使用RestTemplate进行feignclient调用(附源码)

导读:本篇文章讲解 使用RestTemplate进行feignclient调用(附源码),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

使用RestTemplate进行feignclient调用(附源码)

问题背景

feignclient的本质其实也是http调用,只是进行了封装,通过nacos可以进行服务名调用,并且可以使用负载均衡,除了使用注解@FeignClient进行feign调用,也可以使用RestTemplate进行调用,本篇介绍使用RestTemplate进行调用feign
注意事项:

项目搭建

1 引入pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yg</groupId>
    <artifactId>resttemplate</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>resttemplate</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--StringUtils RandomStringUtils-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
        <!--Lists Maps-->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>31.0.1-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-codec</artifactId>
                    <groupId>commons-codec</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--Feign LoadBalanced-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.2.5.RELEASE</version>
            <exclusions>
                <exclusion>
                    <artifactId>spring-cloud-context</artifactId>
                    <groupId>org.springframework.cloud</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>archaius-core</artifactId>
                    <groupId>com.netflix.archaius</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>jsr305</artifactId>
                    <groupId>com.google.code.findbugs</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--MapUtils-->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
        <!--注册中心-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
            <version>2.2.0.RELEASE</version>
            <exclusions>
                <exclusion>
                    <artifactId>guava</artifactId>
                    <groupId>com.google.guava</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>HdrHistogram</artifactId>
                    <groupId>org.hdrhistogram</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-cloud-commons</artifactId>
                    <groupId>org.springframework.cloud</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>commons-codec</artifactId>
                    <groupId>commons-codec</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>commons-lang3</artifactId>
                    <groupId>org.apache.commons</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>httpclient</artifactId>
                    <groupId>org.apache.httpcomponents</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-cloud-starter</artifactId>
                    <groupId>org.springframework.cloud</groupId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2 添加bootstrap连接注册中心

server:
  port: ${SERVER_PORT:1994}

spring:
  application:
    name: resttemplate-feign
  cloud:
    nacos:
      discovery:
        server-addr: ${REGISTER_HOST:10.10.196.247}:${REGISTER_PORT:8848}
      config:
        server-addr: ${REGISTER_HOST:10.10.196.247}:${REGISTER_PORT:8848}
        file-extension: yml

3 RestTemplate配置类

package com.yg.resttemplate.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @Author suolong
 * @Date 2022/5/30 21:53
 * @Version 2.0
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    @LoadBalanced //添加该注解,可以直接通过服务名找到对应的IP地址
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

4 启动类,需要使能feign

package com.yg.resttemplate;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@EnableConfigurationProperties
@SpringBootApplication
public class ResttemplateApplication {

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

}

5 http工具类

package com.yg.resttemplate.utils;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.yg.resttemplate.plugins.CustomJacksonHttpMessageConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Slf4j
@Service
public class HttpClientPoolUtils implements InitializingBean {

    private PoolingHttpClientConnectionManager poolConnManager;
    private RequestConfig requestConfig;
    private CloseableHttpClient httpClient;

    /**
     * Spring封装的http请求对象。
     */
    private static RestTemplate restTemplate;

    /**
     * 并发控制锁对象。
     */
    private static final Object LOCK_REST_TEMPLATE = new Object();

    // region 获取全局对象

    /**
     * 获取Spring封装的http请求对象。
     *
     * @return http请求对象。
     */
    @Bean
    @LoadBalanced
    private static RestTemplate getRestTemplate() {
        if (null == restTemplate) {
            synchronized (LOCK_REST_TEMPLATE) {
                if (null == restTemplate) {

                    // endregion

                    restTemplate = new RestTemplate();
                    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
                        /**
                         * 返回的状态不等于200,不抛出异常
                         *
                         * @param response
                         * @throws IOException
                         */
                        @Override
                        public void handleError(ClientHttpResponse response) throws IOException {
                        }

                        /**
                         * 忽略非200错误
                         *
                         * @param response
                         */
                        @Override
                        public boolean hasError(ClientHttpResponse response) throws IOException {
                            return true;
                        }
                    });

                    // 替换默认的 Jackson 消息转换器实现
                    List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
                    Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
                    while (iterator.hasNext()) {
                        HttpMessageConverter<?> next = iterator.next();
                        if (next instanceof MappingJackson2HttpMessageConverter) {
                            iterator.remove();
                            break;
                        }
                    }
                    messageConverters.add(new CustomJacksonHttpMessageConverter());
                }
            }
        }

        return restTemplate;
    }

    // endregion

    private static void config(HttpRequestBase httpRequestBase, Map<String, Object> header) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(20000)
                .setConnectTimeout(20000)
                .setSocketTimeout(20000).build();
        httpRequestBase.addHeader("Content-Type", "application/json;charset=UTF-8");
        if (MapUtils.isNotEmpty(header)) {
            for (Map.Entry<String, Object> entry : header.entrySet()) {
                httpRequestBase.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        httpRequestBase.setConfig(requestConfig);
    }

    private void initPool() {
        try {
            restTemplate = getRestTemplate();

            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
                    "http", PlainConnectionSocketFactory.getSocketFactory()).register(
                    "https", sslsf).build();
            poolConnManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            poolConnManager.setMaxTotal(500);
            poolConnManager.setDefaultMaxPerRoute(500);

            int socketTimeout = 1200000;
            int connectTimeout = 100000;
            int connectionRequestTimeout = 100000;
            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
                    connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
                    connectTimeout).build();
            httpClient = getConnection();
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            e.printStackTrace();
        }
    }

    private CloseableHttpClient getConnection() {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(poolConnManager)
                .setDefaultRequestConfig(requestConfig)

                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, false))
                .build();
        return httpClient;
    }

    public String postForForm(String url, Map<String, String> reqMap) {
        long start = System.currentTimeMillis();
        CloseableHttpResponse response = null;
        String result = StringUtils.EMPTY;
        HttpPost httpPost = null;

        try {
            // 创建httpPost
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
            for (Map.Entry<String, String> entry : reqMap.entrySet()) {
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //发送post请求
            response = httpClient.execute(httpPost);

            if (null == response) {
                return "请求撞库平台异常";
            }
            if (null != response.getStatusLine() && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

                return result;
            } else {
                log.error("bad response, result: {}", EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
            }
        } catch (Exception e) {
            log.error("=============[\"异常\"]======================", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;

    }


    public String postRestTemplateForm(String url, MultiValueMap<String, String> params, JSONObject header) {
        try {
            HttpHeaders headers = new HttpHeaders();
            List<String> values = Lists.newArrayList();
            values.add("application/x-www-form-urlencoded");
            values.add(String.format("multipart/form-data;boundary=%s", RandomStringUtils.randomNumeric(14)));
            headers.put("Content-Type", values);
            List<MediaType> mediaTypeList = new ArrayList<>();
            mediaTypeList.add(MediaType.ALL);
            headers.setAccept(mediaTypeList);

            org.springframework.http.HttpEntity<MultiValueMap<String, String>> requestEntity = new org.springframework.http.HttpEntity<>(params, headers);

            ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, JSONObject.class);
            if (null != response.getBody()) {
                return response.getBody().toJSONString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("resttemplate表单提交失败:{}", ex.getLocalizedMessage());
        }
        return null;
    }


    public String postRestTemplateJson(String url, String jsonStr, Map<String, Object> headerMap) {
        try {
            HttpHeaders headers = new HttpHeaders();
            if (MapUtils.isNotEmpty(headerMap)) {
                for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
                    final String key = entry.getKey();
                    final String value = (String) entry.getValue();
                    if (StringUtils.isAnyEmpty(key, value)) {
                        continue;
                    }
                    headers.add(key, value);
                }
            }
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            // headers.add("GlobalId", globalId);
            org.springframework.http.HttpEntity<String> requestEntity = new org.springframework.http.HttpEntity<>(jsonStr, headers);
            return Objects.requireNonNull(restTemplate.postForObject(url, requestEntity, String.class));
        } catch (Exception ex) {
            log.error("resttemplate表单提交失败:{}", ex.getLocalizedMessage());
        }
        return null;
    }

    public String restTemplateMock(String url, String jsonStr) {
        String response = restTemplate.postForObject(url, jsonStr, String.class);
        log.info("response={}", response);
        return response;
    }


    public String postForJson(String url, String jsonStr, Map<String, Object> headerMap) {
        long start = System.currentTimeMillis();
        CloseableHttpResponse response = null;
        try {

            // 创建httpPost
            HttpPost httpPost = new HttpPost(url);
            if (MapUtils.isNotEmpty(headerMap)) {
                for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
                    final String key = entry.getKey();
                    final String value = (String) entry.getValue();
                    if (StringUtils.isAnyEmpty(key, value)) {
                        continue;
                    }
                    httpPost.setHeader(key, value);
                }
            }
            httpPost.setHeader("Accept", "application/json");

            StringEntity entity = new StringEntity(jsonStr, "UTF-8");
            entity.setContentType("application/json");
            entity.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(entity);
            //发送post请求
            response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity());
                log.debug("request success cost = {}, result = {}", System.currentTimeMillis() - start, result);
                return result;
            } else {
                log.error("bad response: {}", JSONObject.parseObject(EntityUtils.toString(response.getEntity())));
            }
        } catch (Exception e) {
            log.error("=============[\"异常\"]======================, e: {}", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public String post(String url, String jsonStr) {
        log.debug("url = " + url + " ,  json = " + jsonStr);
        long start = System.currentTimeMillis();
        CloseableHttpResponse response = null;
        String result = StringUtils.EMPTY;
        try {
            // 创建httpPost
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");

            StringEntity entity = new StringEntity(jsonStr, "UTF-8");
            entity.setContentType("application/json");
            entity.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(entity);
            //发送post请求
            response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity());
                log.debug("request success cost = {}, result = {}", System.currentTimeMillis() - start, result);
                return result;
            } else {
                log.error("bad response, result: {}", EntityUtils.toString(response.getEntity()));
            }
        } catch (Exception e) {
            log.error("=============[\"异常\"]======================, e: {}", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public String get(String url) {
        HttpGet httpGet = new HttpGet(url);
        config(httpGet, null);
        return getResponse(httpGet);
    }

    public String getWithHeader(String url, Map<String, Object> header) {
        HttpGet httpGet = new HttpGet(url);
        config(httpGet, header);
        return getResponse(httpGet);
    }

    private String getResponse(HttpRequestBase request) {
        CloseableHttpResponse response = null;
        try {

            response = httpClient.execute(request,
                    HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);

            return result;
        } catch (IOException e) {
            log.error("send http error", e);
            return "";
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }


    public JSONObject postForJsonObject(String url, String jsonStr) throws Exception {
        log.debug("url = " + url + " ,  json = " + jsonStr);
        long start = System.currentTimeMillis();
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");

        StringEntity entity = new StringEntity(jsonStr, "UTF-8");
        entity.setContentType("application/json");
        entity.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
        httpPost.setEntity(entity);
        //发送post请求
        CloseableHttpResponse response = httpClient.execute(httpPost);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            JSONObject result = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            log.debug("request success cost = {}, result = {}", System.currentTimeMillis() - start, result);
            return result;
        } else {
            log.error("bad response: {}", JSONObject.parseObject(EntityUtils.toString(response.getEntity())));
        }

        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initPool();
    }

}

6 测试controller,get和post接口

package com.yg.resttemplate.controller;

import com.alibaba.fastjson.JSON;
import com.yg.resttemplate.service.RestTemplateService;
import com.yg.resttemplate.utils.HttpClientPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author suolong
 * @Date 2022/5/30 21:36
 * @Version 2.0
 */
@Slf4j
@RestController
@RequestMapping("resttemplate")
public class RestTemplateController {

    @Autowired
    RestTemplateService restTemplateService;

    @Autowired
    HttpClientPoolUtils httpClientPoolUtils;

    @GetMapping("/getRestTemplateTest")
    public String getRestTemplateTest() {
        log.info("I am getRestTemplateTest");
        return "I am getRestTemplateTest";
    }


    @PostMapping("/postRestTemplateTest")
    public String postRestTemplateTest(@RequestBody String msg) {
        String res = "I am postRestTemplateTest " + msg;
        log.info(res);
        return res;
    }

    @PostMapping("/select")
    public String select(@RequestParam Integer number) {
        String res = null;
        switch (number) {
            case 1:
                res = restTemplateService.restTemplateGet1();
                break;
            case 2:
                res = restTemplateService.restTemplatePost1();
                break;
            case 3:
                res = restTemplateService.restTemplateGet2();
                break;
            case 4:
                res = restTemplateService.restTemplatePost2();
                break;
            case 5:
                res = restTemplateService.restTemplateGet3();
                break;
            case 6:
                res = restTemplateService.restTemplatePost3();
                break;
            case 7:
                res = httpClientPoolUtils.postRestTemplateJson("http://resttemplate-feign/resttemplate/postRestTemplateTest", "I am yuange", null);
                break;
        }
        log.info(res);
        return res;
    }
}

7 转换插件

package com.yg.resttemplate.plugins;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.ArrayList;
import java.util.List;


public class CustomJacksonHttpMessageConverter extends MappingJackson2HttpMessageConverter {
    public CustomJacksonHttpMessageConverter() {
        this(Jackson2ObjectMapperBuilder.json().build());
    }

    public CustomJacksonHttpMessageConverter(ObjectMapper objectMapper) {
        super(objectMapper);
        // 这里是重点,增加支持的类型,看你的情况加
        // 我这里目前只需要加个 TEXT/PLAIN
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.ALL);
        setSupportedMediaTypes(mediaTypes);
    }
}

8 各种http测试方法

package com.yg.resttemplate.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author suolong
 * @Date 2022/5/30 21:31
 * @Version 2.0
 */
@Slf4j
@Service
public class RestTemplateService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;


    public String restTemplateGet1() {
        // 新建对象
        RestTemplate restTemplate = new RestTemplate();

        String response = restTemplate.getForObject("http://localhost:1994/resttemplate/getRestTemplateTest", String.class);
        log.info("response: {}", response);
        return response;
    }


    public String restTemplatePost1() {
        // 新建对象
        RestTemplate restTemplate = new RestTemplate();
        //请求目标地址
        String requestMsg = "方式一 POST 请求";
        String response = restTemplate.postForObject("http://localhost:1994/resttemplate/postRestTemplateTest", requestMsg, String.class);
        log.info("response: {}", response);
        return response;
    }


    public String restTemplateGet2() {
        // 获取IP地址
        ServiceInstance choose = loadBalancerClient.choose("resttemplate-feign");
        String url = String.format("http://%s:%s", choose.getHost(), choose.getPort() + "/resttemplate/getRestTemplateTest");
        log.info("url: {}", url);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        log.info("response: {}", response);
        return response;
    }


    public String restTemplatePost2() {
        // 获取IP地址
        ServiceInstance choose = loadBalancerClient.choose("resttemplate-feign");
        // 组装URL
        String url = String.format("http://%s:%s", choose.getHost(), choose.getPort() + "/resttemplate/postRestTemplateTest");
        RestTemplate restTemplate = new RestTemplate();
        String requestMsg = "方式二 POST loadBalancerClient";
        String response = restTemplate.postForObject(url, requestMsg, String.class);
        log.info("response: {}", response);
        return response;
    }


    public String restTemplateGet3() {

        String requestMsg = "方式三 GET";
        String response = restTemplate.getForObject("http://resttemplate-feign/resttemplate/getRestTemplateTest", String.class);
        log.info("response: {}", response);
        return response;
    }


    public String restTemplatePost3() {

        String requestMsg = "方式三 POST";
        String response = restTemplate.postForObject("http://resttemplate-feign/resttemplate/postRestTemplateTest", requestMsg, String.class);
        log.info("response: {}", response);
        return response;
    }
}

9 项目目录结构
使用RestTemplate进行feignclient调用(附源码)

项目测试

1 打开postman,选择1-7,输入测试的方法

        switch (number) {
            case 1:                                           //直接使用url调用
                res = restTemplateService.restTemplateGet1();
                break;
            case 2:                                          //直接使用url调用
                res = restTemplateService.restTemplatePost1();
                break;
            case 3:                                          //使用LoadBalancerClient自动选择一个url和port调用
                res = restTemplateService.restTemplateGet2();
                break;
            case 4:                                          //使用LoadBalancerClient自动选择一个url和port调用
                res = restTemplateService.restTemplatePost2();
                break;
            case 5:                                          //使用服务名自己调用
                res = restTemplateService.restTemplateGet3();
                break;
            case 6:                                          //使用服务名自己调用
                res = restTemplateService.restTemplatePost3();
                break;
            case 7:                                          //使用服务名自己调用
                res = httpClientPoolUtils.postRestTemplateJson("http://resttemplate-feign/resttemplate/postRestTemplateTest", "I am yuange", null);
                break;

使用RestTemplate进行feignclient调用(附源码)

心得

第一次使用RestTemplate调用feign,感觉还不错哦

作为程序员第 146 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …
使用RestTemplate进行feignclient调用(附源码)使用RestTemplate进行feignclient调用(附源码)使用RestTemplate进行feignclient调用(附源码)

Lyric: 有一条热昏头的响尾蛇

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/110729.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!